Section 8/81 menit
8. Ringkasan
8. Ringkasan
Kapan Pack Iteration vs Alternatif
swift
Semua elemen punya tipe yang sama?
└── YA → Gunakan Array<T> atau [any Protocol]
Lebih simple, runtime flexible
Tipe berbeda, jumlah FIXED?
└── YA → Gunakan tuple atau multiple parameters
func process(_ a: Int, _ b: String, _ c: Bool) { }
Tipe berbeda, jumlah VARIABEL, butuh type-safety?
└── YA → Parameter Packs + Pack Iteration ← use case utama
Contoh: validation framework, DI container, assertion helpers
Butuh tambah/hapus elemen saat runtime?
└── YA → Array<any Protocol> atau existential collection
Pack di-resolve compile-time, tidak bisa dinamis
Sintaks Cheat Sheet
swift
// Deklarasi
func f<each T>(_ values: repeat each T) { }
// Dengan constraint
func f<each T: Equatable>(_ values: repeat each T) { }
// Return pack
func f<each T>(_ values: repeat each T) -> (repeat each T) {
(repeat each values)
}
// Pack iteration (Swift 6)
for value in repeat each values {
print(value)
}
// Collect ke Array
var results: [String] = []
for value in repeat each values {
results.append("\(value)")
}
// Zip dua pack
for (a, b) in repeat each (firstPack, secondPack) {
process(a, b)
}
Learning Path
- Mulai dengan: Generic functions biasa (
<T>) - Lanjut ke: Multiple type parameters (
<T, U>) - Kemudian: Parameter packs dasar (
<each T>,repeat each T) - Akhirnya: Pack iteration (Swift 6) untuk logika yang lebih kompleks
Pack iteration adalah fitur yang jarang dibutuhkan di aplikasi sehari-hari, tapi menjadi sangat powerful saat membangun framework, testing library, atau validation engine yang harus bekerja dengan multiple tipe secara type-safe.
Dibuat: 2026-05-08 | Swift 6.0