Last active
July 11, 2020 17:10
-
-
Save mattyoung/c50ec4bc5f0748a982890afcc6cc783b to your computer and use it in GitHub Desktop.
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
protocol Record: Equatable { | |
func save() | |
} | |
extension Record { | |
func save() { | |
// save to disk | |
print("Record: Disk") | |
} | |
} | |
struct User: Record { | |
let name: String | |
func save() { | |
// save to server | |
print("User: Server") | |
} | |
// Some User capability | |
func doUserThing() { | |
print("Doing thing") | |
} | |
} | |
func expectARecord<R: Record>(_ record: R) { | |
record.save() | |
} | |
// Problem: user her is only a Record, not a User | |
let user: some Record = User(name: "Jane Doe") | |
// error: 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions | |
//let makeNoSense = User(name: "Paul") as some Record | |
user.save() // user's static type is Record, its dynamic type is User, so save will do according to user. | |
//user.doUserThing() // <=== no can do! | |
// This let user be a User and a Record fully | |
let userFully = User(name: "Jane Doe") | |
userFully.save() // Save according to User's implementation | |
expectARecord(userFully) | |
userFully.doUserThing() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment