1

With Xcode installed, I would like to compile and run a .swift file in the command line. Understood, this can be done:

xcrun swift sayHello.swift

However, I would like to pass an argument in the command line.

For example, with the following function in sayHello.swift:

func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"
    return greeting
}

How do you pass an argument, e.g. Bob? This looked promising:

-D Specifies one or more build configuration options

xcrun swift -D sayHello(Bob) sayHello.swift

But, it's not what I expected.

bucephalus
  • 89
  • 1
  • 5

1 Answers1

0

You can pass arbitrary strings as command-line arguments to the process, but you cannot expect that they are executed as code (like sayHello(Bob)).

In Swift, Process.arguments is a string array with all command-line arguments given to the process. The first element (at index 0) is the path to the executable itself, and the additional command-line arguments start at index 1:

// sayHello.swift

func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"
    return greeting
}

let args = Process.arguments
for i in 1 ..< args.count {
    let name = args[i]
    let greeting = sayHello(name)
    println(greeting)
}

Example:

$ xcrun swift sayHello.swift Peter Paul Mary
Hello, Peter!
Hello, Paul!
Hello, Mary!
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382