Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 578
Kaktusiarz Avatar asked Aug 18 '16 21:08

Kaktusiarz


People also ask

Can enum have functions in Swift?

Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.

Are Swift enums value types?

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.

Can enum be used as variable type?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

How do you declare an enum variable?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.


1 Answers

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)
}
like image 54
MirekE Avatar answered Sep 20 '22 13:09

MirekE