我想在调用函数之前检查它是否存在。例如:
if let touch: AnyObject = touches.anyObject() {
let location = touch.locationInView(self)
touchMoved(Int(location.x), Int(location.y))
}
我想调用 touchMoved(Int, Int) 如果存在的话。是否可以?
您可以使用可选的链接运算符:
这似乎只适用于定义了@可选函数的 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
奇怪的是,在上面的示例中,协议“SomeRandomProtocol”甚至没有为“SomeRandomClass”声明......但是如果没有协议定义,链接运算符会给出错误 - 至少在操场上是这样。似乎编译器需要先前声明的函数原型才能使 ?() 运算符正常工作。
似乎那里可能存在一些错误或工作要做。
有关可选链接运算符及其在这种情况下如何工作的更多信息,请参阅“深度快速互操作性”会议。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)