Hashbang Swift
An easy way to run a swift code from the Terminal is by setting the hashbang (#!
).
#!/usr/bin/xcrun swift -i
func hanoi<T>(numberOfDisks n :Int, fromRod f: T, toRod t: T, usingRod u: T, closure: (T, T) -> ()) {
if n > 0 {
hanoi(numberOfDisks: n - 1, fromRod: f, toRod: u, usingRod: t, closure)
closure(f, t)
hanoi(numberOfDisks: n - 1, fromRod: u, toRod: t, usingRod: f, closure)
}
}
hanoi(numberOfDisks: 4, fromRod: "A", toRod: "B", usingRod: "C") {
println("Move from \($0) to \($1)")
}
Once the hashbang is set, the file can have its mode bits changed to make it executable.
$ chmod +x hanoi.swift
And, finally, Swift running from the terminal:
$ ./hanoi.swift
Move from A to C
Move from A to B
Move from C to B
Move from A to C
Move from B to A
Move from B to C
Move from A to C
Move from A to B
Move from C to B
Move from C to A
Move from B to A
Move from C to B
Move from A to C
Move from A to B
Move from C to B
But note that the swift
command is installed by Xcode 6, and it's not visible while Xcode 5 is the default Xcode set for development. To make it visible, it's necessary to switch to Xcode 6 by running the command xcrun
$ xcrun -s /Application/Xcode6-Beta2.app
Written by Otavio Cordeiro
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#