我希望在调用它之前检查是否存在func.例如: if let touch: AnyObject = touches.anyObject() { let location = touch.locationInView(self) touchMoved(Int(location.x), Int(location.y)) } 我想调用touchMoved(Int,Int),如果它存在
if let touch: AnyObject = touches.anyObject() {
let location = touch.locationInView(self)
touchMoved(Int(location.x), Int(location.y))
}
我想调用touchMoved(Int,Int),如果它存在的话.可能吗?
您可以使用可选的链接运算符:这似乎只适用于定义了@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
奇怪的是,在上面的例子中,协议“SomeRandomProtocol”甚至没有为“SomeRandomClass”声明……但是如果没有协议定义,链接操作符会给出错误 – 至少在操场上.好像编译器需要先前为?()运算符声明的函数原型才能工作.
似乎可能有一些错误或工作要做.
有关可选链接运算符的更多信息以及它在这种情况下的工作原理,请参阅“深入的快速互操作性”会话.
