Swift 4の複数行文字列リテラルとプロトコル合成機能

複数行文字列リテラルの実装

Swift 4では三重引用符による文字列定義が可能となりました。次のような実装例をご覧ください:

let configuration = """
{
  "endpoint": "https://api.example.com",
  "timeout": 30,
  "headers": {
    "Content-Type": "application/json"
  }
}
"""

let escapedExample = """
JSONエスケープ例: \\n 改行文字と \\\\\\" 二重引用符
終端三重引用符のエスケープ: \\\"\"\"
"""

func fetchConfig() -> String {
    return """
        {
          "endpoint": "https://api.example.com",
          "timeout": 30
        }
        """
}

print(configuration == fetchConfig()) // trueを出力

この機能の特徴として:

  • 開始・終了の三重引用符は文字列内容に含まれない
  • 終端三重引用符直前のインデントは自動削除される
  • コード内の整形を維持したまま文字列を定義可能

プロトコル合成型の活用

複数のプロトコルを組み合わせた型定義が可能になりました。実装例:

protocol Authenticated {
    var sessionToken: String { get }
}
protocol RateLimited {
    var requestQuota: Int { get }
}

struct ApiService: Authenticated, RateLimited {
    var sessionToken: String
    var requestQuota: Int
}

func executeSecureRequest(service: Authenticated & RateLimited) {
    print("トークン: \(service.sessionToken), 残りリクエスト: \(service.requestQuota)")
}

let client = ApiService(
    sessionToken: "x-auth-7f3a9b",
    requestQuota: 100
)
executeSecureRequest(service: client)

この構文はObjective-Cのid<Protocol1, Protocol2>に相当し、型安全なマルチプロトコル要件を実現します。

キー パス式の拡張

動的なプロパティアクセスにキー パス式が導入されました:

struct UserProfile {
    struct Contact {
        var email: String
    }
    var contactInfo: Contact
}

let profile = UserProfile(
    contactInfo: .init(email: "user@example.com")
)

let emailPath = \UserProfile.contactInfo.email
print(profile[keyPath: emailPath]) // user@example.com

let users = [
    UserProfile(contactInfo: .init(email: "a@example.com")),
    UserProfile(contactInfo: .init(email: "b@example.com"))
]
let firstEmail = users[keyPath: \[UserProfile].first?.contactInfo.email]
print(firstEmail ?? "N/A") // a@example.com

列挙値の列挙処理

CaseIterableプロトコルを採用した列挙型では、すべてのケースを列挙可能です:

enum HTTPMethod: CaseIterable {
    case get, post, put, delete, patch
}

print("サポートメソッド数: \(HTTPMethod.allCases.count)") // 5

for method in HTTPMethod.allCases {
    switch method {
    case .get: print("取得操作")
    case .post: print("新規作成")
    default: print("その他の操作")
    }
}

タグ: Swift4 StringLiterals ProtocolComposition KeyPathExpressions CaseIterable

7月3日 16:25 投稿