A Beginner’s Guide to Scripting in Swift

THE STORY…

Compiling Swift Source Files.
//====================Swift 1.2 Code===================="        
//let kraken = mythicalBeast as! Kraken        
//====================Old Swift Code====================" //       
let kraken = mythicalBeast as Kraken
//==========================End========================="

ACTUALLY SCRIPTING IN SWIFT

#!/usr/bin/swift
$ chmod +x main.swift
#!/usr/bin/swift 

import Foundation 
class MythicalBeast { 
    func whatsMyName() { 
        println("I don't know what I am, but I'm the stuff of legends.") 
    } 
} 

class Kraken: MythicalBeast { 
    override func whatsMyName() { 
        println("I'm the Kraken, yo!") 
    } 
} 

//can't use the Kraken class until after the declaration 
let kraken = Kraken() kraken.whatsMyName()
$./main.swift 
I'm the Kraken, yo!
$ ./main.swift firstArgument secondArgument thirdArgument
dump(Process.arguments)
$ ./main.swift firstArgument secondArgument thirdArgument 
▿ 4 elements
    - [0]: ./main.swift   
    - [1]: firstArgument   
    - [2]: secondArgument   
    - [3]: thirdArgument
With great power comes great responsibility.

USING SWIFTC TO MAKE THINGS A LITTLE EASIER

$ swiftc main.swift -o kraken //The parameter after -o is the name you really want your script to be called other than "main".
$ xcrun -sdk macosx swiftc kraken.swift -o kraken
<unknown>:0: error: cannot load underlying module for 'CoreGraphics'
<unknown>:0: note: did you forget to set an SDK using -sdk or SDKROOT?
<unknown>:0: note: use "xcrun -sdk macosx swift" to select the default OS X SDK installed with Xcode
alias swiftc='xcrun -sdk macosx swiftc'
$ swiftc main.swift -o kraken
$ ./kraken

PRO-TIP #1

$ swiftc one.swift two.swift three.swift -o combined.swift

PRO-TIP #2

$ sudo cp kraken /usr/bin
$ kraken firstArgument secondArgument etc

CATO — A NEAT LIBRARY BY @NEONACHO

CONCLUSION


Capital One Tech

The low down on our high tech from the engineering experts at Capital One. Learn about the solutions, ideas and stories driving our tech transformation.

Hector Matos

Written by

iOS Developer @capitalone. Family man. SuperWhoLockian. Hero of Time. An odd INTP. Sometimes goes by Tom Oliver.

Capital One Tech

The low down on our high tech from the engineering experts at Capital One. Learn about the solutions, ideas and stories driving our tech transformation.