如何使swift中的协议方法成为可选的?
如何使swift中的协议方法成为可选的?现在协议中的所有方法似乎都是必需的。还有其他解决方法吗?要使用可选方法,请使用如何使swift中的协议方法成为可选的?,swift,delegates,protocols,Swift,Delegates,Protocols,如何使swift中的协议方法成为可选的?现在协议中的所有方法似乎都是必需的。还有其他解决方法吗?要使用可选方法,请使用@objc @objc protocol MyProtocol { optional func someMethod(); } 如。所述,虽然您可以在Swift 2中使用@objc,但您可以添加默认实现,而无需自己提供方法: protocol Creatable { func create() } extension Creatable { //
@objc
@objc protocol MyProtocol {
optional func someMethod();
}
如。所述,虽然您可以在Swift 2中使用
@objc
,但您可以添加默认实现,而无需自己提供方法:
protocol Creatable {
func create()
}
extension Creatable {
// by default a method that does nothing
func create() {}
}
struct Creator: Creatable {}
// you get the method by default
Creator().create()
但是,在Swift 1.x中,您可以添加一个包含可选闭包的变量
protocol Creatable {
var create: (()->())? { get }
}
struct Creator: Creatable {
// no implementation
var create: (()->())? = nil
var create: (()->())? = { ... }
// "let" behavior like normal functions with a computed property
var create: (()->())? {
return { ... }
}
}
// you have to use optional chaining now
Creator().create?()
如果我的回答对你有帮助,请投票并接受它。谢谢