swift sh - 外部ライブラリを用いたSwiftスクリプトを実行
SwiftはiOSやmacOSアプリを作るのに使われるプログラミング言語ですが、今はサーバサイドでも使えるようになっています。活用範囲が広がることで、ターミナルのスクリプトとして使いたいと思う人もいるでしょう。 もちろん使えるのですが、外部ライブラリを利用しようと思うとビルドする必要があり、非常に手間です。そこで使ってみたいのがswift shです。
swift shの使い方
例えば以下のようなコードがあります。
#!/usr/bin/swift sh
import Foundation
import PromiseKit // @mxcl ~> 6.5
firstly {
after(.seconds(2))
}.then {
after(.milliseconds(500))
}.done {
print("notice: two and a half seconds elapsed")
exit(0)
}
RunLoop.main.run()
PromiseKitを使っているので外部ライブラリがなく、通常は実行できません。
$ swift foo.swift
foo.swift:4:8: error: no such module 'PromiseKit'
import PromiseKit // @mxcl ~> 6.5
^
そこでswift shを使います。
$ swift sh foo.swift
notice: two and a half seconds elapsed
ちゃんと実行できました。
swift shを使うことでサードパーティーライブラリを使っているSwiftのスクリプトでもちゃんと実行できます。最初はダウンロードが行われるようですが、二回目以降の実行は速いです。Swiftが好きな方はぜひ使ってみましょう。
swift shはSwift製のオープンソース・ソフトウェア(Public Domain)です。
mxcl/swift-sh: Easily script with third-party Swift dependencies