Enumeration and Tuples in Swift
Enumerations in Swift
It defines a common type for a group of related values. They provide a type-safe way to work with these values.
Example:
enum CompassPoint {
case north
case south
case east
case west
}
Associated Values:
Enum cases can store associated values of any type, allowing them to carry additional data.
Example:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
Raw Values:
Enums can also have raw values of a specific type (e.g., Int, String).
Example:
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
let earthOrder = Planet.earth.rawValue // 3
Tuples in Swift
It allows grouping multiple values into a single compound value. These values can be of different types.
Example:
let http404Error = (404, "Not Found")
Accessing Tuple Elements:
Elements can be accessed by their index or by naming them.
let (statusCode, statusMessage) = http404Error // Decomposing
print("The status code is \(statusCode)") // Output: The status code is 404
let namedTuple = (code: 200, message: "OK")
print(namedTuple.message) // Output: OK