Kaktusiarz
Kaktusiarz

Reputation: 425

Swift - how to declare variable/functon of/with enums of different type?

I need to declare variable which will store array of enums of different type, eg.:

var enums = [EnumTypeA.Option1, EnumTypeB.Option2]

Compiler states:

Type of expression is ambiguous without more context

This will be necessary to pass any enum or other object as a function parameter. However I discovered that I can pass generics to achieve this, eg.:

func f1<T>(enum: T)

but having protocol with optional methods (prefixed with @objc) it is impossible.

Upvotes: 9

Views: 332

Answers (2)

MirekE
MirekE

Reputation: 11555

You can use a protocol...

protocol MyEnums {}

enum MyEnum1: MyEnums {
    case first, second
}

enum MyEnum2: MyEnums {
    case red, green
}

let myArray: [MyEnums] = [MyEnum1.first, MyEnum2.green]

func myFunc(myEnum: MyEnums) {
    print(myEnum)
}

for value in myArray {
    myFunc(myEnum: value)
}

Upvotes: 2

CodeBender
CodeBender

Reputation: 36620

This was fun. Instead of generics, I just went with Any, since that is the base of everything.

enum TypeA {
    case Option1
    case Option2
}

enum TypeB {
    case Option1
    case Option2
}

func acceptDifferentEnums(value: Any) {
    switch value {
    case let typeA as TypeA:
        print("This is TypeA")
    case let typeB as TypeB:
        print("This is typeB")
    default:
        print("This is something else")
    }
}


acceptDifferentEnums(TypeA.Option1) // This is TypeA
acceptDifferentEnums(TypeB.Option2) // This is TypeB
acceptDifferentEnums("Foo") // This is something else

You then use the switch statement to downcast the value property into your various enums, and process them accordingly.

Upvotes: 1

Related Questions