Section 3/81 menit

3. Sintaks Dasar

3. Sintaks Dasar

Deklarasi Type Pack

swift
// 'each' dalam generic parameter list = type pack
func example<each T>() { }

// Dengan constraint — semua tipe dalam pack harus conform
func example<each T: Equatable>() { }

// Multiple packs
func zip<each A, each B>() { }

Pack Parameter

swift
// 'repeat each T' sebagai parameter type = value pack
func printAll<each T>(_ values: repeat each T) {
    repeat print(each values)  // pack expansion dalam body
}

// Pemanggilan:
printAll(1, "hello", true, 3.14)
//       ─  ───────  ────  ────
//    Int   String   Bool  Double  ← T = (Int, String, Bool, Double)

Pack dalam Tuple

swift
// (repeat each T) adalah tuple type yang di-expand dari pack
func asTyple<each T>(_ values: repeat each T) -> (repeat each T) {
    return (repeat each values)  // pack expansion dalam return
}

let tuple = asTuple(1, "hello", true)  // (Int, String, Bool)
print(tuple.0)  // 1
print(tuple.1)  // "hello"
print(tuple.2)  // true