As I tried following code, I get some Errors.
enum Operate: ((Double, Double) -> Double) = {
case Plus = {$1 + $0}
case Minus = {$1 - $0}
case Multiply = {$1 * $0}
case Divide = {$1 / $0}
}
Is it possible to create a Enum in Swift with Raw Values type of a Closure ? Thanks.
The Problem with Associated Values We had to do this because Swift doesn't allow us to have both: raw values and associated values within the same enum. A Swift enum can either have raw values or associated values.
Each raw value for our enum case must be a unique string, character, or value of any integer or floating-point type. This means the value for the two case statements cannot be the same.
Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. So, A has a fixed raw value of 0 , B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case).
Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.
As @Pang said, only Strings, Characters or any integer of floating-point number types can be used as the raw type. However, you could achieve something similar using a struct
:
struct Operate {
typealias OperationType = (Double, Double) -> Double
static let Plus : OperationType = { $0 + $1 }
static let Minus: OperationType = { $0 - $1 }
// ...
}
let plus = Operate.Plus
plus(1.0, 2.0) // 3.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With