簡単な Swift script を書くときは
println("hello world")
% swift sample.swift
hello world
swift コマンドを使う事で実行できます。
#!/usr/bin/env swift
println("hello world")
% chmod +x sample.swift
% ./sample.swift
shebang をつければ上記のようでもOK。
CocoaPods を一緒に使いたいけど
例えば普通に Xcode で SwiftyJSON
を使いたいときは CocoaPods を使うと簡単に使えるのですが、Swift script で使おうと思うと、ビルドしてどうこうでめんどうです。(というか、私はその方法がまだよく分かってないです。。)
Apous
https://github.com/owensd/apous
作者のブログ
CocoaPods
や Carthage
の依存を解決して Swift script を実行できるみたいです。
導入
Homebrew への Pull Request を出しているみたいですが、まだ受理されていないみたいなので、Release からバイナリをダウンロードする必要があります。
https://github.com/owensd/apous/releases から apous.zip
のある Release のリンクからダウンロードして解凍します。
とりあえず /usr/local/bin/
に入れて実行権限だけ付けておきましょう。
% apous -help
OVERVIEW: Apous Swift Script Runner (build: 0.2.0-master)
USAGE: apous [<script_file>|<path/to/scripts>]
上記が実行できればインストールは成功です。(短時間でバージョン上がっていくので、いつまでこれでいけるか分からないですが)
使ってみる
CocoaPods 無し
import Foundation
print("Welcome to Apous!")
let url = NSURL(string: "http://api.tiqav.com/search/random.json")
var request = NSURLRequest(URL: url!)
let response = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
let response_body :String = NSString(data: response!, encoding: NSUTF8StringEncoding) as! String
var json: NSArray = NSJSONSerialization.JSONObjectWithData(response!, options:NSJSONReadingOptions.AllowFragments, error: nil) as! NSArray
print(json)
直接関係ないですが Foundation を import して以下が出るときがあります。
:0: error: cannot load underlying module for CoreGraphics
:0: note: did you forget to set an SDK using -sdk or SDKROOT?
:0: note: use "xcrun -sdk macosx swift" to select the default OS X SDK installed with Xcode
その場合は export SDKROOT=$(xcrun --show-sdk-path --sdk macosx) を指定する必要があります。
Foundation
は標準で使えるのでこのままで問題無いです。よって普通の swift コマンドでも実行可能です。
% swift sample.swift
# or
% apous .
ファイルを指定する場合は main.swift である必要があります
実行後には .apousscript
が生成されている事がわかります。
shebang でも実行できる
書いてる途中で機能が追加されてた。。main.swift
をエントリポイントにする必要があるようです。
#!/usr/local/bin/apous
//後は同じ
% chmod +x main.swift
% ./main.swift
CocoaPods で SwiftyJSON を使ってみる
platform :osx, '10.10'
use_frameworks!
pod 'SwiftyJSON', '~> 2.2.0'
#!/usr/local/bin/apous
import Foundation
import SwiftyJSON
let url = NSURL(string: "http://api.tiqav.com/search/random.json")
var request = NSURLRequest(URL: url!)
let response = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
let json = JSON(data: response!)
println(json)
これでいいんですが、どうやら今の 0.2.0 だとダメで、0.1.1 とかなら大丈夫のようですね。(逆に 0.1.1 だと shebang がまだ入ってないんですが)
ちょっとコードちゃんと読めておらず原因は分かりません。。
妄想
Swift の REPL は便利なんですが、依存ライブラリをちょっと試す時に Ruby の bundle console のような手軽さが無いように思います。(知らないだけであるのかもしれないですし Playground もあるので、bundle console みたいのは不要なのかもしれませんが。。)
Apous みたいな仕組みで bundle console みたいに Xcode 立ちあげなくても気軽にライブラリの実験ができるといいなぁと。
私はまだ Xcode も Swift も始めたばかりで自前のビルドも満足にできないので Apous のコードは色々と参考になりそうです。