I was interested in performing system calls from Swift, and I found a resource that I had to modify somewhat. I imagine that the language has changed since that post was written. At any rate, here is the working code,
#!/usr/bin/env xcrun swift import Foundation let task = NSTask() task.launchPath = "/bin/ls" task.arguments = ["-alh"] let pipe = NSPipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: NSString = NSString( data: data, encoding: NSUTF8StringEncoding )! print( output )
Two things stood out to me: line 6 requires the full path of the ls
command, which is probably a performance thing, and the NSString
call at line 14 requires the encoding, which seems like a real pain to remember to type out all the time.