Last active
July 25, 2018 15:51
-
-
Save yanli0303/8bbc668446430715f6a5b48aa11371eb to your computer and use it in GitHub Desktop.
Swift 4 extension default implementation vs. inheritance
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 Cocoa | |
// see https://team.goodeggs.com/overriding-swift-protocol-extension-default-implementations-d005a4428bda | |
protocol ToString { | |
func toString() -> String | |
} | |
extension ToString { | |
func toString() -> String { | |
return "extension default implementation" | |
} | |
} | |
class Person: ToString { | |
func print() { | |
Swift.print(toString()) | |
} | |
} | |
class Student: Person { | |
// override extension default implementation | |
func toString() -> String { | |
return "Student" | |
} | |
} | |
let person = Person() | |
person.print() // extension default implementation | |
let student = Student() | |
student.print() // extension default implementation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment