Last active
August 5, 2020 13:14
Protocols, inheritance, default implementations, and optional methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol P { | |
var required: String { get } | |
} | |
extension P { | |
var required: String { "Default implementation of `required`" } | |
var nonRequired: String { "Default implementation of `nonRequired`" } | |
} | |
class C: P { | |
var required: String { "Superclass implementation of `required`" } | |
var nonRequired: String { "Superclass implementation of `nonRequired`" } | |
} | |
class D: C { | |
override var required: String { "Subclass implementation of `required`" } | |
override var nonRequired: String { "Subclass implementation of `nonRequired`" } | |
} | |
for p in [C(), D()] as [P] { | |
print("\(p) as P: \(p.required)") | |
print("\(p) as P: \(p.nonRequired)") | |
} | |
for c in [C(), D()] as [C] { | |
print("\(c) as C: \(c.required)") | |
print("\(c) as C: \(c.nonRequired)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment