How can I make a protocol method in swift optional? Now all the methods in a protocol is seems to be required. Is there any other work arounds?
While you can use @objc in Swift 2 you can add a default implementation and you don't have to provide the method yourself:
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()
However in Swift 1.x you could add a variable which holds an optional closure
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?()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With