Reputation: 1099
I need to convert a variable from NSUInt to Int to pass it as argument to allocate.
I tried initializing with Int() but the compiler refuses cannot invoke initializer for type 'int' with an argument of type '(UInt?)'
this is the variable: NSUInteger count
this is the call to allocatelet outPut = UnsafeMutablePointer<Float>.allocate(capacity: count)
Without the conversion the compiler generates this error:
cannot convert value of type 'UInt?' to expected argument type 'Int'
Upvotes: 1
Views: 849
Reputation: 51891
It's because it is optional, you need to unwrap it
var x: UInt?
if let z = x {
let y = Int(exactly: z)
}
Note that Int(exactly:)
returns an optional as well so you might want to use a guard
statement or another if let...
Update, as pointed out by vacawama Int(z) might crash
Upvotes: 2
Reputation: 3157
You need to use bit pattern initialiser.
let unsignedInt = Int(bitPattern: UInt)
But this will not take care overflow situations.
Upvotes: 0