Search code examples
swiftswift3c-stringsunsafe-pointers

How to use UnsafePointer with Swift 3


I am trying to use the function made by Martin R as an answer to this question: Get terminal output after a command swift

However, the UnsafePointer line no longer works with Swift 3 and I'm having trouble figuring it out. How would I adapt this code to Swift 3?

if var string = String.fromCString(UnsafePointer(outdata.bytes)) {
    string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
    output = string.componentsSeparatedByString("\n")
}

ps, You need to "Import Cocoa" if you want to trying using the function.


Solution

  • In Swift 3, readDataToEndOfFile() returns a Data value, not NSData. The answer to your direct question would be

    let data: Data = ...
    let string = data.withUnsafeBytes { String(cString: UnsafePointer<CChar>($0)) }
    

    However, that requires a NUL-terminated sequence of bytes (so that wasn't my smartest idea in Get terminal output after a command swift and I'll update that later).

    Better use String(data: encoding:):

    let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String(data: outdata, encoding: .utf8) {
        string = string.trimmingCharacters(in: .newlines)
        output = string.components(separatedBy: "\n")
    }