Tuples trong Swift
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
// Tuple đơn giản
let point = (10, 20)
let person = ("Alice", 25, "alice@email.com")
// Với named elements
let namedPoint = (x: 10, y: 20)
let user = (name: "Bob", age: 30)3. Truy cập phần tử
let person = ("Alice", 25, "NYC")
// Theo index
print(person.0) // Alice
print(person.1) // 25
print(person.2) // NYC
// Với named elements
let point = (x: 10, y: 20)
print(point.x) // 10
print(point.y) // 204. Decomposition (Destructuring)
let person = ("Alice", 25, "NYC")
// Decompose into separate variables
let (name, age, city) = person
print(name) // Alice
print(age) // 25
// Ignore values với _
let (nameOnly, _, _) = person
print(nameOnly) // Alice5. 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
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
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
// 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ế
// HTTP Response
func fetch() -> (statusCode: Int, data: String?, error: String?) {
return (200, "Success", nil)
}
let response = fetch()
if response.statusCode == 200 {
print(response.data ?? "No data")
}
// Coordinates
func getLocation() -> (latitude: Double, longitude: Double) {
return (21.0285, 105.8542) // Hanoi
}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
- 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
Last updated on
Swift