类型(二) – 枚举

温馨提示:本文最后更新于2024-07-28 16:47:43,某些文章具有时效性,若有错误或已失效,请在下方留言
enum Color {
    case unknown
    case blue
    case green
    case pink
    case purple
    case red
}

枚举的基本使用

struct Toy {
    let name: String
    let color: Color
}

let barbie = Toy(name: "Barbie", color: .pink)
let raceCar = Toy(name: "Lighting McQueen", color: .red)

原始值

原始值是每个枚举的基础数据类型。枚举默认没有原始值,因此如果需要原始值,就需要声明。

enum Color: Int {
    case unknown, blue, green, pink, purple ,red
}

通过添加 :Int,Swift 就为每种颜色赋予了一个匹配的整数,从 0 开始向上计数。

enum Planet: Int {
    case mercury = 1
    case venus
    case earth
    case mars
    case unknown
}

通过特别赋予 Mercury 为 1 的值,Xcode 将从这里开始向上计数:venus 为 2,earth 为 3,mars 为 4。

Planet 枚举中原始值的获取。

let mars = Planet(rawValue: 556) ?? Planet.unknown

无论原始值的数据类型如何,甚至无论是否有原始值,当枚举用作字符串插值的一部分时,Swift 都会自动将其字符串化。

enum Color: String {
    case unknown, blue, green, pink, purple ,red
}

let barbie = Toy(name: "Barbie", color: .pink)
let raceCar = Toy(name: "Lighting McQueen", color: .red)

// regular string interpolation
print("The \(barbie.name) toy is \(barbie.color)")

// get the string form of the Color then call a method on it
print("The \(barbie.name) toy is \(barbie.color.rawValue.uppercased())")

计算属性和方法

Color 枚举添加一个计算属性 description,该属性将打印颜色的简要说明。

enum Color {
    case unknown, blue, green, pink, purple ,red

    var description: String {
        switch self {
        case .unknown:
            return "the color of magic"
        case .blue:
            return "the color of sky"
        case .green:
            return "the color of grass"
        case .pink:
            return "the color of carnations"
        case .purple:
            return "the color of rain"
        case .red:
            return "the color of desire"
        }
    }

    // 计算方法
    func forBoys() -> Bool {
        return true
    }
    
    // 计算方法
    func forGrils() -> Bool {
        return true
    }
}

struct Toy {
    let name: String
    let color: Color
}

let barbie = Toy(name: "Barbie", color: .pink)

print("The \(barbie.name) toy is \(barbie.color.description)")
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容