MarqueIV MarqueIV - 1 year ago 35
Swift Question

How do you declare an argument of type 'enum' (i.e. it can take any enum)?

In C#, you can write a function that takes any enumeration value as an argument by declaring the argument as type

, like so...

public enum FirstEnum

public enum SecondEnum

public void StoreValue(Enum key, object value)
myDictionary[key] = value; <-- Uses the enum as a key

StoreValue(FirstEnum.A, someItem); // Using the first enum type
StoreValue(SecondEnum.D, someItem); // Using the second enum type
StoreValue("Sam", someItem); // Won't compile since 'Sam' is not an enum

Can you do something similar in Swift? I know you can declare the argument
as a string and use it that way, but I'm trying to find out if it can be enforced to be an Enum like you can in C#.

Answer Source

Following Wain's suggestion, you can write something like this:

Create a protocol

public protocol StringKeyEnum
    var rawValue: String {get}

Define the enums and make them adhere to the protocol

enum FirstEnum: String, StringKeyEnum
    case A,
    case B
    case C

enum SecondEnum: String, StringKeyEnum
    case D
    case E
    case F

How to use it

var myDictionary: [String: AnyObject] = [:]

public func storeValue(key: StringKeyEnum, value: AnyObject)
    myDictionary[key.rawValue] = value //<-- Uses the rawValue of enum as a key

let someItem = ""
storeValue(FirstEnum.A,  value: someItem) // Using the first enum type
storeValue(SecondEnum.D, value: someItem) // Using the second enum type
storeValue("Sam",        value: someItem) // Won't compile since 'Sam' is not a StringKeyEnum