Skip to content

Instantly share code, notes, and snippets.

@alfavata
Last active August 5, 2020 13:14
Show Gist options
  • Save alfavata/dedfd7700d722ec68d283284849df778 to your computer and use it in GitHub Desktop.
Save alfavata/dedfd7700d722ec68d283284849df778 to your computer and use it in GitHub Desktop.
Protocols, inheritance, default implementations, and optional methods
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