Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare swift generic for enums of particular type?

Tags:

swift

Would it be possible to have a function that allows any enum where the rawValue is of a certain type? For example, any enum that has a string rawValue.

like image 775
moger777 Avatar asked Feb 09 '15 16:02

moger777


People also ask

Can enums be generic?

Enums can have multiple generic parameters.

Can enum conform to Swift protocol?

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.

Can enums have variables Swift?

An enum is a special type of variable that is specifically used with switch and conditionals. Swift enumeration cases don't have unique default integer values (like an array), unlike languages such as TypeScript and Objective C where the first element has a value of 0 , the second a value of 1 , and so on.


1 Answers

This can be done using generics and the "where" keyword

enum EnumString: String {
    case A = "test"
}

func printEnum<T: RawRepresentable where T.RawValue == String>(arg: T) {
    print(arg.rawValue)
}
printEnum(EnumString.A) //Prints "test"
like image 178
Jeremy Conkin Avatar answered Oct 15 '22 10:10

Jeremy Conkin