Iacopo Boccalari
Iacopo Boccalari

Reputation: 1245

system() command with a variable in Swift

Here I come with another noob question: I'm trying to write a very simple program in Swift and got stuck when trying to run a shell command from within the program using a variable.

A quick example: writing system("say hello") works.

But the following code doesn't work:

var whatToSay = "hello world"
system("say \(whatToSay)")

The error I get when building the program is: Could not find member 'convertFromStringInterpolatingSegment'

Any help?

Upvotes: 4

Views: 2170

Answers (2)

Diego Freniche
Diego Freniche

Reputation: 5414

In Swift 2.1 (Xcode 7.1), if you need to run a command like say in OS X you can also use NSTask, as shown in this blog post

Basically, something along the lines of (if you don't need to check command output, that is):

import Foundation

let task = NSTask()
task.launchPath = "/usr/bin/say"
task.arguments = ["Hello", "World!"]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

Upvotes: 1

Zaphod
Zaphod

Reputation: 7290

You need to cast to obtain CString:

var whatToSay = "hello world"
var nsCommand : NSString = "say \(whatToSay)"
var command : CString? = nsCommand.cStringUsingEncoding(NSUTF8StringEncoding)
system(command!)

EDIT:

If you use it often, you can use an extension for String:

extension String {
    func toCString() -> CString? {
        let nsSelf : NSString = self
        return nsSelf.cStringUsingEncoding(NSUTF8StringEncoding)
    }
}

var whatToSay = "hello world"
system("say \(whatToSay)".toCString()!)

Upvotes: 5

Related Questions