Created
April 6, 2016 18:15
-
-
Save jackhl/83ad1dddba7fe149b962a3aeed2a86f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// only class types: | |
func myCast<MyClass: AnyObject>(value: AnyObject, type: MyClass.Type) -> MyClass? { | |
return value as? MyClass | |
} | |
// any type (class, struct, etc): | |
func myCast1<MyClass: Any>(value: Any, type: MyClass.Type) -> MyClass? { | |
return value as? MyClass | |
} |
This is brilliant, thank you!
Also: http://blog.segiddins.me/2015/01/25/dynamic-casting-in-swift/
Non-optional version may be useful if you're brave / sure:
func infer<T: Any>(value: Any) -> T {
return value as! T
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't even need the
type:
parameter if you're fine with relying on return-type type inference e.g. this would work if you defined the same function but without thetype:
parameter: