iosswift

iOS: Convert UnsafeMutablePointer<Int8> to String in swift?


As the title says, what is the correct way to convert UnsafeMutablePointer to String in swift?

//lets say x = UnsafeMutablePointer<Int8> 

var str = x.memory.????

I tried using x.memory.description obviously it is wrong, giving me a wrong string value.


Solution

  • If the pointer points to a NUL-terminated C string of UTF-8 bytes, you can do this:

    import Foundation
    
    let x: UnsafeMutablePointer<Int8> = ...
    // or UnsafePointer<Int8>
    // or UnsafePointer<UInt8>
    // or UnsafeMutablePointer<UInt8>
    
    let str = String(cString: x)