LoginSignup
424
423

More than 5 years have passed since last update.

Swiftをシェルスクリプトのように使う一番簡単な方法

Last updated at Posted at 2014-11-11

Update: Apple Swift version 2.1 (swiftlang-700.1.101.6 clang-700.1.76) 用に書き直しました。

hello.swift

#!/usr/bin/swift

let hello = "こんにちは"
print(hello)

// 遊び心で。。
let 挨拶 = "お世話になります"
print(挨拶)

$ chmod a+x hello.swift
$ ./hello.swift

これだけです。/usr/bin/swiftで動作を確認しています。

$ /usr/bin/swift --version
Apple Swift version 2.1 (swiftlang-700.1.101.6 clang-700.1.76)
Target: x86_64-apple-darwin15.0.0

肝は、

#!/usr/bin/swift をファイルの先頭に記述することのみです。

お試しあれ。

この仕組みを使って、IPAファイルの生成コマンドを作ってみました。

注意: このコードはSwift1.0対応のままで更新していません
https://gist.github.com/naokits/5e202549d0fc96f3e3c6

追記:

実際に動作する、JSONを取得する簡単なSwiftスクリプトを貼り付けておきます。

sample_script.swift

#!/usr/bin/swift

import Foundation

typealias Failure = (NSError!) -> Void
typealias ResultBlock = (NSData!, NSError!) -> Void

/// JSONObjectWithDataの戻り値として使用する
enum JSONObjectWithDataResult {
    case Success(AnyObject)
    case Failure(NSError)
}

/// NSDataをJSONオブジェクトに変換し、JSONオブジェクトまたはエラーのいずれかを返す
func JSONObjectWithData(data: NSData) -> JSONObjectWithDataResult {
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        return .Success(json)
    } catch let error as NSError {
        return .Failure(error)
    }
}

/// JSONデータの取得
func fetchJSONData(block: ResultBlock) {
    let url = NSURL(string: "http://api.tiqav.com/search/random.json")
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)
    let task = session.dataTaskWithURL(url!) { data, response, error in
        guard let data = data else {
            block(nil, error)
            return
        }
        session.invalidateAndCancel()
        dispatch_async(dispatch_get_main_queue()) { () in
            block(data, nil)
        }
    }
    task.resume()
}

var waitingForBlock = true // 終了判定で使用する

fetchJSONData() { data, error in

    guard let data = data else {
        print("エラー: \(error)")
        return
    }

    switch JSONObjectWithData(data) {
    case .Success(let json):
        print("json: \(json)")
        for item in json as! [NSDictionary] {
            print(item.objectForKey("source_url"))
        }
    case .Failure(let error):
        print("エラー: \(error)")
    }

    waitingForBlock = false
}

while waitingForBlock {
    // 1秒毎に終了を確認する
    NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow:1.0))
}

おまけ

カレントディレクトリを表示するだけです。このコードを元に、いろいろ工夫してみてください。

#!/usr/bin/swift

import Foundation

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "ls -l ./"]
task.standardInput = NSFileHandle.fileHandleWithNullDevice()
task.standardError = NSFileHandle.fileHandleWithStandardError()
task.standardOutput = NSFileHandle.fileHandleWithStandardOutput()
task.launch()
task.waitUntilExit()
424
423
10

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
424
423