I want to specify a type constraint that the type should be a raw value enum:
enum SomeEnum: Int { case One, Two, Three } class SomeProtocol<E: enum<Int>> { // <- won't compile func doSomething(e: E) { compute(e.toRaw()) } }
How can I do it in Swift? (I used the F# syntax for example)
In Swift, we can also assign values to each enum case. For example, enum Size : Int { case small = 10 case medium = 12 ... } Here, we have assigned values 29 and 31 to enum cases small and medium respectively.
Swift enum syntax To define an enum in Swift, use the keyword enum followed by the name of the enum. The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized.
Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.
In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
enum SomeEnum: Int { case One, Two, Three } class SomeClass<E: RawRepresentable where E.RawValue == Int>{ func doSomething(e: E) { print(e.rawValue) } } class SomeEnumClass : SomeClass<SomeEnum> { }
or directly
class SomeOtherClass{ func doSomething<E: RawRepresentable where E.RawValue == Int>(e: E) { print(e.rawValue) } }
UPDATE for swift3:
enum SomeEnum: Int { case One, Two, Three } class SomeClass<E: RawRepresentable> where E.RawValue == Int { func doSomething(e: E) { print(e.rawValue) } } class SomeEnumClass : SomeClass<SomeEnum> { }
resp.
class SomeOtherClass{ func doSomething<E: RawRepresentable>(e: E) where E.RawValue == Int { print(e.rawValue) } }
While you can place enums into a generic type without contraints (<T>
), it's not possible to create constraints for all enums or all structs. All the constraints are based on interfaces (subclassing, protocols). Unfortunately, there is nothing in common between two random structs or two random enums.
Structs and enums can't inherit from other structs/enums so the only constraints for enums must be based on protocols.
protocol EnumProtocol { func method() } enum TestEnum : Int, EnumProtocol { case A case B func method() { } } enum TestEnum2 : Int, EnumProtocol { case C func method() { } } class EnumGeneric <T : EnumProtocol> { func method(a: T) { a.method() } } let test = EnumGeneric<TestEnum>() test.method(TestEnum.A)
Also note that all enums "inheriting" from a primitive type like Int
conform to RawRepresentable
, so you could
class EnumGeneric <T : RawRepresentable> { func method(a: T) { println("\(a.toRaw())"); } }
but that won't work for enums declared as enum TestEnum {
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