我在谷歌上搜索了一下,但没有找到与respondsToSelector:等价的swift:是什么。
这是我唯一能找到的(Swift替代respondsToSelector),但在我的情况下并不太相关,因为它检查委托的存在,我没有委托,我只是想检查在设备上运行时是否存在新的API,如果没有回落到API的以前版本。
我在谷歌上搜索了一下,但没有找到与respondsToSelector:等价的swift:是什么。
这是我唯一能找到的(Swift替代respondsToSelector),但在我的情况下并不太相关,因为它检查委托的存在,我没有委托,我只是想检查在设备上运行时是否存在新的API,如果没有回落到API的以前版本。
当前回答
我只是在一个项目中实现了这一点,见下面的代码。正如@Christopher Pickslay提到的,重要的是要记住函数是第一类公民,因此可以像可选变量一样对待。
@objc protocol ContactDetailsDelegate: class {
optional func deleteContact(contact: Contact) -> NSError?
}
...
weak var delegate:ContactDetailsDelegate!
if let deleteContact = delegate.deleteContact {
deleteContact(contact)
}
其他回答
斯威夫特3:
协议
@objc protocol SomeDelegate {
@objc optional func method()
}
对象
class SomeObject : NSObject {
weak var delegate:SomeObject?
func delegateMethod() {
if let delegateMethod = delegate?.method{
delegateMethod()
}else {
//Failed
}
}
}
如果你要测试的方法在@objc协议中被定义为可选方法(听起来像你的情况),那么使用可选的链接模式为:
if let result = object.method?(args) {
/* method exists, result assigned, use result */
}
else { ... }
当方法被声明为返回Void时,只需使用:
if object.method?(args) { ... }
See:
通过可选链接调用方法 摘自:苹果公司《快速编程语言》。 iBooks。https://itun.es/us/jEUH0.l
我使用guard let else,如果委托func没有实现,它可以做一些默认的事情。
@objc protocol ViewController2Delegate: NSObjectProtocol {
optional func viewController2(controller: ViewController2, didSomethingWithStringAndReturnVoid string: String)
optional func viewController2(controller: ViewController2, didSomethingWithStringAndReturnString string: String) -> String
}
class ViewController2: UIViewController {
weak var delegate: ViewController2Delegate?
@IBAction func onVoidButtonClicked(sender: AnyObject){
if (delegate != nil && delegate!.respondsToSelector(Selector("viewController2:didSomethingWithStringAndReturnVoid:"))) {
NSLog("ReturnVoid is implemented")
delegate!.viewController2!(self, didSomethingWithStringAndReturnVoid: "dummy")
}
else{
NSLog("ReturnVoid is not implemented")
// Do something by default
}
}
@IBAction func onStringButtonClicked(sender: AnyObject){
guard let result = delegate?.viewController2?(self, didSomethingWithStringAndReturnString: "dummy") else {
NSLog("ReturnString is not implemented")
// Do something by default
return
}
NSLog("ReturnString is implemented with result: \(result)")
}
}
我只是在一个项目中实现了这一点,见下面的代码。正如@Christopher Pickslay提到的,重要的是要记住函数是第一类公民,因此可以像可选变量一样对待。
@objc protocol ContactDetailsDelegate: class {
optional func deleteContact(contact: Contact) -> NSError?
}
...
weak var delegate:ContactDetailsDelegate!
if let deleteContact = delegate.deleteContact {
deleteContact(contact)
}
函数在Swift中是一类类型,所以你可以通过将协议中定义的可选函数与nil进行比较来检查它是否已经实现:
if (someObject.someMethod != nil) {
someObject.someMethod!(someArgument)
} else {
// do something else
}