枚举相关值

时间:2016-04-05 11:39:38

标签: swift enums

我正在试图了解Swift的Enum。我想为我的枚举案例分配一个关联的值并返回一个计算值。目前我正在使用一种方法来返回计算出的数字。

enum Calculation {
    case Number1(number: Int)
    case Number2(number: Int)

    func calculation() -> Int {
        switch self {
        case Number1(let number): return number + 1
        case Number2(let number): return number + 2
        }
    }
}

我想知道它是否可以更短,如:

// This obviously doesn't work. Just an example as what I'm trying to achieve
enum Calculation: Int {
    case Number1(number: Int): return number + 1
    case Number2(number: Int): return number + 2
}

1 个答案:

答案 0 :(得分:2)

问题是您是否要使用计算变量:

enum Calculation {
    case Number1(number: Int)
    case Number2(number: Int)

    var value:Int {
        switch self {
        case Number1(let number): return number + 1
        case Number2(let number): return number + 2
        }
    }

}

或将值存储为关联值:

enum CalculationType {
    case Number1, Number2
}
enum Calculation {

    case Number1(number: Int)
    case Number2(number: Int)

    init (type:CalculationType, number:Int) {
        switch type {
        case .Number1:
            self = Calculation.Number1(number: number + 1)
        case .Number2:
            self = Calculation.Number2(number: number + 2)
        }

    }
}

你的问题指向前者,但我不清楚你的第二段代码是否期望后者或希望初始化会返回一个不会发生的值({{1} }}不返回值)。最接近的是拥有一个静态函数:

init

或者,您可以在enum CalculationType { case Number1, Number2 } enum Calculation { case Number1(number: Int) case Number2(number: Int) static func calc(type:CalculationType, number:Int) -> (Calculation, Int) { switch type { case .Number1: return (Calculation.Number1(number: number), number + 1) case .Number2: return (Calculation.Number2(number: number), number + 2) } } } Calculation.calc(.Number1, number: 2) 上使用回调:

init