我希望在调用之前检查 func 是否存在。例如:

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

如果存在,我想调用 touchMoved(Int, Int) 。是否可以?

最佳答案

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

这似乎只适用于定义了 @optional 函数的 ObjC 协议(protocol)。似乎还需要对 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

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

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

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

关于swift - 检查 Swift 中是否存在 func,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24174422/

10-10 21:06
查看更多