我希望在调用它之前检查是否存在func.例如:
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”声明……但是如果没有协议定义,链接操作符会给出错误 – 至少在操场上.好像编译器需要先前为?()运算符声明的函数原型才能工作.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。