Skip to content

Instantly share code, notes, and snippets.

@toineheuvelmans
Last active February 13, 2017 13:29
Show Gist options
  • Save toineheuvelmans/30b1a8f68bf14f04e9da5f2832fc49fc to your computer and use it in GitHub Desktop.
Save toineheuvelmans/30b1a8f68bf14f04e9da5f2832fc49fc to your computer and use it in GitHub Desktop.
Optional protocol functions in Swift (without @objc).
protocol MyFancyProtocol {
func requiredFunction() -> String
func optionalFunction() -> String
}
extension MyFancyProtocol {
func optionalFunction() -> String {
return "Default implementation of optionalFunction"
}
func nonProtocolFunction() -> String {
return "Default implementation of nonProtocolFunction"
}
}
struct MyAwesomeObject : MyFancyProtocol {
func requiredFunction() -> String {
return "Awesome implementation of requiredFunction"
}
func nonProtocolFunction() -> String {
return "Awesome implementation of nonProtocolFunction"
}
}
struct MyOtherAwesomeObject : MyFancyProtocol {
func requiredFunction() -> String {
return "Other awesome implementation of requiredFunction"
}
func optionalFunction() -> String {
return "Other awesome implementation of optionalFunction"
}
}
func run(object: MyFancyProtocol) {
print(object.requiredFunction())
print(object.optionalFunction())
print(object.nonProtocolFunction())
}
run(object: MyAwesomeObject())
//> Awesome implementation of requiredFunction
//> Default implementation of optionalFunction
//> Default implementation of nonProtocolFunction
run(object: MyOtherAwesomeObject())
//> Other awesome implementation of requiredFunction
//> Other awesome implementation of optionalFunction
//> Default implementation of nonProtocolFunction
@toineheuvelmans
Copy link
Author

The description was capped. Anyway, here it is in its entirety:
This small snippet shows how to implement optional protocol functions in Swift (without @objc).
You can define a default implementation in a protocol extension. Any implementation in a type conforming to your protocol will be called in favor of the default implementation, as long as the function is defined in the protocol.
If both the protocol extension and your conforming type implement a function with the same signature but one that is not defined in the protocol, the implementation defined in the protocol extension will be called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment