gpt4 book ai didi

swift - 你可以在枚举中使用闭包作为 Swift 中的参数吗?

转载 作者:行者123 更新时间:2023-11-28 13:27:53 25 4
gpt4 key购买 nike

如果你在 Swift 中有一个接受闭包的函数,你能否强制参数只包含在枚举中的值,就像使用 init() 完成的那样?

// function that takes a closure as a param

func calculator (n1: Int, n2: Int, operation: (Int, Int) -> Int) -> Int {
return operation(n1, n2)
}

// sample call. Note: I'd like the closure to be an enum so that the programmer can only pick from items listed in the enum.

let myCalc = calculator(n1: 5, n2: 6 ) {$0 * $1}

// list of valid choices in an enum

enum CalcOptions {
case Add {$0 + $1}
case Subtract {$0 - $1}
case Multiply {$0 * $1}
case Divide {$0 / $1}
}

// Note: this gives an error (can't have the closure on the same line), I'd like the elements in CalcOptions to be closures.

// I can't do this because it's not a type listed:

var calcClosure: Closure {
switch self {
case .Add: return {$0 + $1}
case .Subtract: return {$0 - $1}
case .Multiply: return {$0 * $1}
case .Divide: return {$0 / $1}
}
}

如果您想限制使用枚举中列出的那些选项,就像您在设置 init() 时所做的那样,您会怎么做?

据我所知,当您在 init() 中使用枚举时,它会像数据类型一样工作,这样 init 的用户只能从出现的列表中进行选择。

我希望在函数中具有相同的功能,这样用户只能从枚举中列出的元素中进行选择。

类中的示例,其中 customerChosenType 在 init() 中被限制为 CarType...

enum CarType {
case Sedan
case Coupe
case Hatchback
case FastBack
}

init(customerChosenType : CarType){
typeOfCar01 = customerChosenType
}

最佳答案

Swift 枚举不能将闭包作为 rawValues,因此您可能需要以其他方式绑定(bind)每个 case 及其对应的闭包,例如:

enum CalcOptions {
case add
case subtract
case multiply
case divide
}
extension CalcOptions {
var operation: (Int, Int)->Int {
switch self {
case .add: return {$0 + $1}
case .subtract: return {$0 - $1}
case .multiply: return {$0 * $1}
case .divide: return {$0 / $1}
}
}
}

func calculator (n1: Int, n2: Int, option: CalcOptions) -> Int {
return option.operation(n1, n2)
}
print(calculator(n1: 2, n2: 3, option: .add)) //->5

或者,如果您使用的是 Swift 5+,则可以使您的枚举可调用:

@dynamicCallable
enum CalcOptions {
case add
case subtract
case multiply
case divide

func dynamicallyCall(withArguments args: [Int])->Int {
let n1 = args[0], n2 = args[1]
switch self {
case .add:
return n1 + n2
case .subtract:
return n1 - n2
case .multiply:
return n1 * n2
case .divide:
return n1 / n2
}
}
}

func calculator(n1: Int, n2: Int, operation: CalcOptions) -> Int {
return operation(n1, n2)
}
print(calculator(n1: 2, n2: 3, operation: .multiply)) //->6

关于swift - 你可以在枚举中使用闭包作为 Swift 中的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048947/

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