Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Type Casts in Swift
func typecast<T,U>(_ a:T) -> U {
var _a = a
return withUnsafePointer(to: &_a) { (ptr:UnsafePointer<T>) -> U in
return UnsafeRawPointer(ptr).load(as: U.self)
}
}
func typecast_inplace<T,U>(_ a:inout T) -> U {
return withUnsafePointer(to: &a) { (ptr:UnsafePointer<T>) -> U in
return UnsafeRawPointer(ptr).load(as: U.self)
}
}
// Usage:
let bignum:UInt64 = 0xAAAAAAAABBBBBBBB
struct parts {
var a:UInt32
var b:UInt32
}
let a:parts = typecast(bignum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment