Narwhal Narwhal - 1 month ago 10
Swift Question

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.

Answer

In Swift 3, readDataToEndOfFile() returns a Data value and that can easily be converted to a string with 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")
}
Comments