【问题标题】:Check if a func exists in Swift检查 Swift 中是否存在 func
【发布时间】:2014-06-11 23:51:34
【问题描述】:

我想在调用它之前检查一个函数是否存在。例如:

    if let touch: AnyObject = touches.anyObject() {
        let location = touch.locationInView(self)
        touchMoved(Int(location.x), Int(location.y))
    }

如果存在,我想调用 touchMoved(Int, Int)。有可能吗?

【问题讨论】:

    标签: swift func


    【解决方案1】:

    您可以使用可选的链接运算符:

    这似乎只适用于定义了 @optional 函数的 ObjC 协议。似乎也需要对 AnyObject 进行强制转换:

    import Cocoa
    
    @objc protocol SomeRandomProtocol {
        @optional func aRandomFunction() -> String
        @optional func anotherRandomFunction() -> String
    }
    
    class SomeRandomClass : NSObject {
        func aRandomFunction() -> String {
            return "aRandomFunc"
        }
    }
    
    var instance = SomeRandomClass()
    (instance as AnyObject).aRandomFunction?()       //Returns "aRandomFunc"
    (instance as AnyObject).anotherRandomFunction?() //Returns nil, as it is not implemented
    

    奇怪的是,在上面的示例中,甚至没有为“SomeRandomClass”声明协议“SomeRandomProtocol”......但是没有协议定义,链接运算符会给出错误 - 至少在操场上。似乎编译器需要先前声明的函数原型才能使 ?() 运算符工作。

    似乎可能有一些错误或工作要做。

    有关可选链接运算符及其在这种情况下如何工作的更多信息,请参阅“深入的快速互操作性”会议。

    【讨论】:

    • 这并不奇怪。在 Objective-C 中也是如此。在ARC下,即使你调用id上的方法,如果没有可见的名为that的方法的声明,也会编译失败。
    猜你喜欢
    • 1970-01-01
    • 2014-10-08
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多