1

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'

Fakher Mokadem
  • 1,059
  • 1
  • 8
  • 22

2 Answers2

2

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

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • This will crash if `x` is too big for an `Int`. I recommend `if let z = x, let y = Int(exactly: z) {` – vacawama Sep 25 '19 at 12:16
0

You need to use bit pattern initialiser.

let unsignedInt = Int(bitPattern: UInt)

But this will not take care overflow situations.

Shreeram Bhat
  • 2,849
  • 2
  • 11
  • 19