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.
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)
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.