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