Created
November 18, 2015 19:26
-
-
Save jepers/fb81ff6c52d32575b00c to your computer and use it in GitHub Desktop.
An example of where I get confused by the interplay between associated types, typealiases and protocol extensions.
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
// I'm using the concept of bits just to make the code a bit more concrete. | |
// The actual use case has nothing to do with implementing type level bits ... | |
// This code compiles and runs as is, but note the last line. | |
// Q: Should this program compile without errors? If so, what should the last line print? | |
protocol BitType {} | |
struct Clr : BitType {} | |
struct Set : BitType {} | |
protocol BitAndOp { | |
typealias A: BitType = Clr | |
typealias B: BitType = Clr | |
typealias Result: BitType = Clr | |
} | |
extension BitAndOp where A == B { | |
typealias Result = Set // This seems to declare a new Result, (since it's ok to set it to non-BitTypes) why? | |
} | |
struct And<T, U where T: BitType, U: BitType> : BitAndOp { | |
typealias A = T | |
typealias B = U | |
} | |
print(And<Set, Clr>.A.self) // Prints Set | |
print(And<Set, Clr>.B.self) // Prints Clr | |
print(And<Set, Clr>.Result.self) // Prints Clr (As expected, since A != B) | |
print(And<Set, Set>.A.self) // Prints Set | |
print(And<Set, Set>.B.self) // Prints Set | |
// print(And<Set, Set>.Result.self) // Uncommenting this line crashes compiler after about ~10 seconds of work, why? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment