虽然您可以@objc在Swift 2中使用,但您可以添加默认实现,而不必自己提供该方法:
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()
Run Code Online (Sandbox Code Playgroud)
但是在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?()
Run Code Online (Sandbox Code Playgroud)
要使用可选方法,请使用标记协议 @objc
@objc protocol MyProtocol {
optional func someMethod();
}
Run Code Online (Sandbox Code Playgroud)