检查Swift中是否存在func
发布时间:2020-12-14 04:32:44 所属栏目:百科 来源:网络整理
导读:我希望在调用它之前检查是否存在func.例如: if let touch: AnyObject = touches.anyObject() { let location = touch.locationInView(self) touchMoved(Int(location.x),Int(location.y)) } 我想调用touchMoved(Int,Int),如果它存在的话.可能吗? 解决方法
我希望在调用它之前检查是否存在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”声明……但是如果没有协议定义,链接操作符会给出错误 – 至少在操场上.好像编译器需要先前为?()运算符声明的函数原型才能工作. 似乎可能有一些错误或工作要做. 有关可选链接运算符的更多信息以及它在这种情况下的工作原理,请参阅“深入的快速互操作性”会话. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |