Processってなに?
ちょっと前までNSTaskと呼ばれていた、主にコマンドラインツールを実行してデータのやり取りを行うためのクラスです。
SwiftでできることはSwiftでやってしまえばいいのですが、swiftcを呼びたいとかそういう時に使います。
ちょっと使ってみよう
では早速使ってみよう。
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が作れないので動かないよ!
文字列だしね!!
演算子の中に隠れちゃってるしね!!
じゃあまた次回!!(たぶん