Swift 枚举可以将函数/闭包作为原始值吗?

问题描述

我知道枚举可以有一个闭包作为关联值,例如:

enum SomeEnum {
    case closureOne (String,Double -> Double)
    case closureTwo (String,(Double,Double) -> Double)
}

但是,枚举可以有一个作为 raw 值的闭包吗?例如,这样的事情有效吗?

enum someEnum: () -> Void {
    case closureOne = doSomething
    case closureTwo  = doSomethingElse
}

哪里

let doSomething = {
    // Do something here.
}

let doSomethingElse {
    // Do something else here.
}

解决方法

它不是那么简单,但您可以使用 OptionSet,参见 this page

与枚举不同,选项集提供了一个不可失败的 init(rawValue:) 初始化器来从原始值转换,因为选项集没有所有可能情况的枚举列表。选项集值与其关联的原始值一一对应。

可能是这样的:

func doSomething() {}
func doSomethingElse() {}

struct MyClosures: OptionSet {

    static let closureOne = MyClosures(rawValue: doSomething)
    static let closureTwo = MyClosures(rawValue: doSomethingElse)

    let rawValue: () -> Void

    init(rawValue: @escaping () -> Void) {
        self.rawValue = rawValue
    }

    init() {
        rawValue = {}
    }

    mutating func formUnion(_ other: __owned MyClosures) {
        // whatever makes sense for your case
    }

    mutating func formIntersection(_ other: MyClosures) {
        // whatever makes sense for your case
    }

    mutating func formSymmetricDifference(_ other: __owned MyClosures) {
        // whatever makes sense for your case
    }

    static func == (lhs: MyClosures,rhs: MyClosures) -> Bool {
        // whatever makes sense for your case
        return false
    }
}

因此您可以将其用作:

let myClosures: MyClosures = [ .closureOne,.closureTwo ]

但是在评论中查看您的解释:

所以我试图找到在给定变量状态的情况下运行函数的最有效方法。

我认为您真正想要的是某种状态机。一些示例可用 herehere