返回
解码小知识:Swift 枚举常见用法概览
IOS
2024-01-29 17:26:27
解码小知识:Swift 枚举常见用法概览
一、关联值
关联值是将额外信息附加到 enum case 中的一种极好的方式。这样当需要传的值变多时,代码无疑就会变得没那么好看了。
enum CoffeeSize {
case small(Double)
case medium(Double)
case large(Double)
}
func coffeePrice(size: CoffeeSize) -> Double {
switch size {
case .small(let price):
return price
case .medium(let price):
return price
case .large(let price):
return price
}
}
使用这种方式可以非常方便地将不同的case值传递给函数。
二、原始值
原始值是枚举 case 可以拥有的实际值。原始值可以是任何类型,包括整数、字符串、浮点数,甚至其他枚举。
enum CompassPoint: String {
case north = "North"
case south = "South"
case east = "East"
case west = "West"
}
let direction: CompassPoint = .north
let directionString = direction.rawValue // "North"
原始值允许你以一种更安全的方式将字符串与枚举值相关联。
三、switch语句
switch语句是处理枚举值最常见的方式。
enum Result<T, E: Error> {
case success(T)
case failure(E)
}
func divide(x: Int, y: Int) -> Result<Int, Error> {
guard y != 0 else {
return .failure(ArithmeticError.divideByZero)
}
return .success(x / y)
}
let result = divide(x: 10, y: 2)
switch result {
case .success(let quotient):
print("The quotient is \(quotient)")
case .failure(let error):
print("An error occurred: \(error)")
}
switch语句允许你以一种更安全的方式处理枚举值。
总之,Swift枚举类型非常强大,可以用来解决各种实际问题,掌握其基本用法和常见用法,可以大大提高编码效率和代码可维护性。