Section 4/81 menit

4. Pack Iteration — Swift 6

4. Pack Iteration — Swift 6

Swift 5.9 memperkenalkan parameter packs, tapi hanya untuk ekspresi tunggal. Swift 6 menambahkan kemampuan untuk iterasi penuh dengan statements:

for ... in repeat each — Swift 6

swift
// Swift 6: iterasi atas pack dengan full statement body
func logAll<each T>(_ values: repeat each T) {
    for value in repeat each values {
        // 'value' punya tipe yang berbeda untuk setiap iterasi
        // body bisa berisi banyak statements
        let description = "\(value)"
        let type = "\(type(of: value))"
        print("[\(type)]: \(description)")
    }
}

logAll(42, "hello", true, 3.14)
// [Int]: 42
// [String]: hello
// [Bool]: true
// [Double]: 3.14

Collecting Results dari Pack Iteration

swift
// Kumpulkan hasil dari setiap elemen pack
func descriptions<each T>(_ values: repeat each T) -> [String] {
    var result: [String] = []
    for value in repeat each values {
        result.append("\(value)")
    }
    return result
}

let desc = descriptions(1, "two", 3.0, true)
// ["1", "two", "3.0", "true"]

Pack Iteration dengan Constraint

swift
// Iterate dan panggil protocol method pada setiap elemen
func validateAll<each T: Validatable>(_ values: repeat each T) -> [ValidationResult] {
    var results: [ValidationResult] = []
    for value in repeat each values {
        results.append(value.validate())  // type-safe: value conform Validatable
    }
    return results
}

protocol Validatable {
    func validate() -> ValidationResult
}

struct ValidationResult {
    let isValid: Bool
    let message: String?
}

Zipping Multiple Packs

swift
// Zip dua pack bersama — seperti zip() di functional programming
func zipWith<each A, each B, Result>(
    _ firstValues: repeat each A,
    _ secondValues: repeat each B,
    combine: (repeat each A, repeat each B) -> Result
) -> Result {
    combine(repeat each firstValues, repeat each secondValues)
}