Tuples
1. Giới thiệu
Phần tiêu đề “1. Giới thiệu”Tuple nhóm nhiều giá trị thành một giá trị compound duy nhất.
2. Tạo Tuple
Phần tiêu đề “2. Tạo Tuple”// Tuple đơn giảnlet point = (10, 20)let person = ("Alice", 25, "alice@email.com")
// Với named elementslet namedPoint = (x: 10, y: 20)let user = (name: "Bob", age: 30)3. Truy cập phần tử
Phần tiêu đề “3. Truy cập phần tử”let person = ("Alice", 25, "NYC")
// Theo indexprint(person.0) // Aliceprint(person.1) // 25print(person.2) // NYC
// Với named elementslet point = (x: 10, y: 20)print(point.x) // 10print(point.y) // 204. Decomposition (Destructuring)
Phần tiêu đề “4. Decomposition (Destructuring)”let person = ("Alice", 25, "NYC")
// Decompose into separate variableslet (name, age, city) = personprint(name) // Aliceprint(age) // 25
// Ignore values với _let (nameOnly, _, _) = personprint(nameOnly) // Alice5. Tuple as Return Type
Phần tiêu đề “5. Tuple as Return Type”func minMax(array: [Int]) -> (min: Int, max: Int)? { guard let first = array.first else { return nil }
var minValue = first var maxValue = first
for value in array { if value < minValue { minValue = value } if value > maxValue { maxValue = value } }
return (minValue, maxValue)}
if let result = minMax(array: [8, 3, 5, 1, 9]) { print("Min: \(result.min), Max: \(result.max)")}6. Tuple trong Switch
Phần tiêu đề “6. Tuple trong Switch”let point = (1, 1)
switch point {case (0, 0): print("Origin")case (_, 0): print("On x-axis")case (0, _): print("On y-axis")case (-2...2, -2...2): print("Inside box")default: print("Outside box")}7. Tuple với Value Binding
Phần tiêu đề “7. Tuple với Value Binding”let point = (2, 0)
switch point {case (let x, 0): print("On x-axis at \(x)")case (0, let y): print("On y-axis at \(y)")case let (x, y): print("At point (\(x), \(y))")}8. So sánh Tuples
Phần tiêu đề “8. So sánh Tuples”// Tuple có thể so sánh theo thứ tựlet a = (1, "apple")let b = (1, "banana")let c = (2, "apple")
print(a < b) // true (so sánh "apple" vs "banana")print(a < c) // true (so sánh 1 vs 2)9. Ví dụ thực tế
Phần tiêu đề “9. Ví dụ thực tế”// HTTP Responsefunc fetch() -> (statusCode: Int, data: String?, error: String?) { return (200, "Success", nil)}
let response = fetch()if response.statusCode == 200 { print(response.data ?? "No data")}
// Coordinatesfunc getLocation() -> (latitude: Double, longitude: Double) { return (21.0285, 105.8542) // Hanoi}10. Giới hạn của Tuple
Phần tiêu đề “10. Giới hạn của Tuple”// Tuple không có tên type// Dùng struct cho complex data
// ❌ Không thể conform protocols// ❌ Không thể extend
// ✅ Dùng cho temporary grouping// ✅ Dùng cho return multiple values📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”- Tuple nhóm nhiều values thành một
- Truy cập bằng index hoặc tên
- Decomposition để extract values
- Phổ biến làm return type
- Pattern matching trong switch
- Dùng struct cho complex data