[英]How can I make a protocol method in swift optional?
如何在swift可選中創建協議方法? 現在似乎需要協議中的所有方法。 還有其他工作嗎?
雖然您可以在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?()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.