Swift Concurrency: URLのlinesを試す

少しでもSwift Concurrencyに慣れていきたい。

開発環境

> xcodebuild -version
Xcode 13.3 Build version 13E113

モチベーション

  • Swift Concurrencyを身体に覚えさせたい

lines (URL)

As a convenience, you can use Swift’s async-await syntax to asynchronously access the contents of a URL through the resourceBytes and lines properties. These properties use the shared URLSession instance to load the resoruce. https://developer.apple.com/documentation/foundation/url

linesはURLのコンテンツに非同期でアクセスできるプロパティ。 プロパティ!?

import Foundation
import _Concurrency

let url = URL(string: "https://tokizuoh.dev/")!

Task {
    for try await line in url.lines {
        print(line)
    }
}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>カルボナーラ街道</title>
...

これだけでリソース(HTMLファイルの中身)を非同期的に取得できる。
以前はどうやってたっけ?

import Foundation

let url = URL(string: "https://tokizuoh.dev/")!

let task = URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data else {
        return
    }
    let value = String(data: data, encoding: .utf8)
    print(value)
}

task.resume()

Optional("<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>カルボナーラ街道</title>\n...

Swift Concurrencyな処理を書いた時と同じ条件(エラーハンドリングなし)で書いた。出力の仕方(一行ずつ or all)が異なるので単純な比較はできないが、前者の方は改行コードが除去済みの値が返ってくるため用途さえ合えば無駄な処理を開発者側で記述しなくて良い。

今後の課題

参考