1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-12-28

Processってなに?

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

の2回目。

第1回
第2回
第3回
第4回

振り返り

前回カスタムオペレーションを2個追加して下のようになりました。

Operations.swift
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
}
let echo = Process() <<< "/bin/echo" <<< ["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)
}

まだ長いわ――!!!!

出力を得るのために長々書かないとだめなのがつらいです。
ここに手を入れます。

出力の取得を簡単に

まず、出力を型にします

struct Output {
    
    private let fileHandle: FileHandle
    
    init(fileHandle: FileHandle) {
        self.fileHandle = fileHandle
    }
    
    var data: Data {
        return fileHandle.readDataToEndOfFile()
    }
    
    var string: String? {
        return String(data: data, encoding: .utf8)
    }
    
    var lines: [String] {
        return string?.components(separatedBy: "\n") ?? []
    }
}

FileHandleからDataStringあるいは行の配列を簡単に取得するための補助的な型です。

使用法

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

let pipe = Pipe()
echo.standardOutput = pipe

echo.launch()

let output = Output(fileHandle: pipe.fileHandleForReading)
if let string = output.string {
    print(string)
}

短い! わかりやすい!

わかりやすい...??

じゃあまた次回!!

第3回
第4回

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?