首页 > 解决方案 > 如何使用那里的子函数获取枚举的 rawValue?

问题描述

我有一个定义如下的枚举。

enum PurchaseTimeType: Int,CaseIterable {
    case ASAP, ThisMonth, NextMonth
    func id() -> Int {
        switch self {
        case .ASAP:
            return 1
        case .ThisMonth:
            return 2
        case .NextMonth:
            return 3
        }
    }
    func title() -> String {
        switch self {
        case .ASAP:
            return "ASAP"
        case .ThisMonth:
            return "This Month"
        case .NextMonth:
            return "Next Month"
        }
    }
}

我已经id存储在一个变量中:

var id = 1

我怎样才能得到title()那个id

标签: swiftenums

解决方案


您将Intid 分配给每个案例,如下所示:

enum PurchaseTimeType: Int, CaseIterable {
    case asap = 1
    case thisMonth = 2
    case nextMonth = 3

    // All above cases can also be written in one line, like so
    // case asap = 1, thisMonth, nextMonth

    var id: Int {
        return self.rawValue
    }

    var title: String {
        switch self {
        case .asap:
            return "ASAP"
        case .thisMonth:
            return "This Month"
        case .nextMonth:
            return "Next Month"
        }
    }

}

用法-1

let purchaseTime: PurchaseTimeType = .thisMonth

print(purchaseTime.id, ":", purchaseTime.title)

Usage-2:按 id 过滤

let id = 1
if let type = PurchaseTimeType.allCases.first(where: { $0.id == id } ) {
    print("Title for \(id) is \(type.title)")
}

注意我从UPPERCASE更新了案例名称以遵循约定,每个案例都应该命名为lowerCamelCase,每个后续单词的第一个字母小写,大写字母。


推荐阅读