Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a Enum in Swift with Raw Values type of a Closure?

Tags:

enums

swift

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.

like image 838
Zheng Avatar asked May 24 '15 10:05

Zheng


People also ask

Can associated values and raw values coexist in Swift enumeration?

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.

What is raw value or associated value in enum in Swift?

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.

What is raw value in enum?

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

Is enum value type in Swift?

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.


1 Answers

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
like image 152
ABakerSmith Avatar answered Sep 28 '22 02:09

ABakerSmith