gpt4 book ai didi

swift - 枚举关联值

转载 作者:搜寻专家 更新时间:2023-11-01 07:25:45 24 4
gpt4 key购买 nike

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

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
}

最佳答案

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

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)
}

}
}

你的问题指向前者,但从你的第二段代码中我不清楚你是期待后者还是希望初始化会返回一个值,这是不可能发生的(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 上使用回调:

enum CalculationType {
case Number1, Number2
}
enum Calculation {

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

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

}

}


Calculation(type: .Number1, number: 10, callback: {n in print(n)})

关于swift - 枚举关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36425369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com