LoginSignup
8
6

More than 5 years have passed since last update.

[Swift] Processを使おう!(1)

Last updated at Posted at 2017-12-26

Processってなに?

ちょっと前までNSTaskと呼ばれていた、主にコマンドラインツールを実行してデータのやり取りを行うためのクラスです。
SwiftでできることはSwiftでやってしまえばいいのですが、swiftcを呼びたいとかそういう時に使います。

第2回
第3回
第4回

ちょっと使ってみよう

では早速使ってみよう。

let echo = Process()
echo.executableURL = URL(fileURLWithPath: "/bin/echo")
echo.arguments = ["Hello, World."]

let pipe = Pipe()
echo.standardOutput = pipe

echo.launch()

let readHandle = pipe.fileHandleForReading
let data = readHandle.readDataToEndOfFile()

if let output = String(data: data, encoding: .utf8) {

    print(output)
}

長いわ――!!!!

Hello, World.をechoコマンドで出力してその出力をprintする。
ただそれだけでこの長さです。
まあ、これではあんまり使おうとは思いませんね。

ということで、これを短くしていきます。
そのままでは無理なのでカスタムオペレーションなどをどんどん書いていきます。

Processのセッティングを簡単に

では、どんどん行きます。
コマンドのパスと引数列を簡単に設定できるようにします。

precedencegroup ArgumentPrecedence {
    associativity: left
    higherThan: AdditionPrecedence
}
func <<< (lhs: Process, rhs: String) -> Process {

    lhs.executableURL = URL(fileURLWithPath: rhs)
    return lhs
}

func <<< (lhs: Process, rhs: [String]) -> Process {

    lhs.arguments = rhs
    return lhs
}

使用法

// original
let echo = Process()
echo.executableURL = URL(fileURLWithPath: "/bin/echo")
echo.arguments = ["Hello, World."]

// New!
let echo = Process() <<< "/bin/echo" <<< ["Hello, World."]

短い! わかりやすい!

問題点

存在しないパスを渡すとURLが作れないので動かないよ!
文字列だしね!!
演算子の中に隠れちゃってるしね!!

じゃあまた次回!!(たぶん

第2回
第3回
第4回

8
6
0

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
8
6