Sasha Vasilev Sasha Vasilev - 3 months ago 23
Objective-C Question

How to convert a type of "any" in kind "UnsafeMutablePointer<Int16>" in a swift 3

I updated my xcode for the latest beta and there was such a problem.
Before my code worked well in objective-c:

short * pointers = (short *)[[params valueForKey:@"Pointers"] pointerValue];


Then I translated part of the code on the swift language:

let pointers = UnsafeMutablePointer<Int16>(((params["Pointers"] as AnyObject).pointerValue)!)


Here, too, everything is good. But this code is not working on the Swift 3. Tell how you can implement on a swift 3. Thank You!

Answer

The correct way of converting a pointer to UInt16 which is wrapped in an NSValue to UnsafeMutablePointer<Int16> in Swift 3 is

if let ptr = value.pointerValue {
    let u16ptr = ptr.assumingMemoryBound(to: UInt16.self)
    // ...
} else {
    // pointer is nil
}

In your case it should be

if let ptr = (params["Pointers"] as? NSValue)?.pointerValue {
    let u16ptr = ptr.assumingMemoryBound(to: UInt16.self)
    // ...
} else {
    // value does not exist, is not an `NSValue`, or pointer is nil
}
Comments