Skip to content

Instantly share code, notes, and snippets.

@jackhl
Created April 6, 2016 18:15
Show Gist options
  • Save jackhl/83ad1dddba7fe149b962a3aeed2a86f7 to your computer and use it in GitHub Desktop.
Save jackhl/83ad1dddba7fe149b962a3aeed2a86f7 to your computer and use it in GitHub Desktop.
// 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
}
@jackhl
Copy link
Author

jackhl commented Apr 6, 2016

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 the type: parameter:

let val: Any = 5
let castVal: Int? = myCast1(value: val)

@mzarra
Copy link

mzarra commented Apr 6, 2016

This is brilliant, thank you!

@garohussenjian
Copy link

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