Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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()
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away