Created
August 21, 2015 19:31
-
-
Save an0/f1698dc2255505c1687f to your computer and use it in GitHub Desktop.
Guard
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 Guard {} | |
class Adam: Guard {} | |
class Alfred: Adam {} | |
func conforms1<T>(x: Any.Type, y: T.Type) -> Bool { | |
return x is T.Type | |
} | |
// This also should be true but for some reason type is Guard.Protocol instead of Guard.Type. | |
print(conforms1(Adam.self, y: Guard.self)) | |
print(conforms1(Adam.self, y: Adam.self)) | |
print(conforms1(Alfred.self, y: Adam.self)) | |
print("---") | |
func conforms2<T>(x: Any.Type, y: T.Type) -> Bool { | |
return x is T | |
} | |
print(conforms2(Adam.self, y: Guard.Type.self)) | |
print(conforms2(Adam.self, y: Adam.Type.self)) | |
print(conforms2(Alfred.self, y: Adam.Type.self)) | |
// Assume this is expensive operation and I want to call only once I know it has a type I want. | |
let obj: () -> Any = { Alfred() } | |
func conforms1<T>(x: Any.Type, y: T.Type, obj: () -> Any) -> T? { | |
if x.dynamicType is T.Type.Type { | |
return obj() as? T | |
} else { | |
return nil | |
} | |
} | |
print(conforms1(Adam.self, y: Guard.self, obj: obj)) | |
print(conforms1(Adam.self, y: Adam.self, obj: obj)) | |
print(conforms1(Alfred.self, y: Adam.self, obj: obj)) | |
print("---") | |
func conforms2<T>(x: Any.Type, y: T.Type.Type, obj: () -> Any) -> T? { | |
if x is T.Type { | |
return obj() as? T | |
} else { | |
return nil | |
} | |
} | |
// print(conforms2(Adam.self, y: Guard.Type.self, obj: obj)) // Everything is good, except for the compiling error of Protocol & Type mismatch here. | |
print(conforms2(Adam.self, y: Adam.Type.self, obj: obj)) | |
print(conforms2(Alfred.self, y: Adam.Type.self, obj: obj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment