Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function enum parameter type

I am new on swift. I have 2+ enums and i would like to create enum to object generator function. I couldn’t find what type I should use for the Enum parameter in my function.

My enums;

public enum Animal: String, CaseIterable {
  case DOG = "dog"
  case CAT = "cat"
  case BIRD = "bird"
}

public enum Car: String, CaseIterable {
  case BMW = "bmw"
  case AUDI = "audi"
}

My Function;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  func enumToObj(Enum:TYPE?) -> Dictionary <String, String> {
    var enumsObject: [String:String] = [:];

    for enumData in Enum.allCases {
        let value = enumData.rawValue;
        enumsObject[value] = value;
    }

    return enumsObject;
  }

 //my expectation
 enumToObj(Animal) && enumToObj(Car)

>Solution :

You can define a generic function which take as argument a type that is CaseIterable and RawRepresentable:

func enumToObj<T>(_ Enum:T.Type) -> [String: T.RawValue]
    where T: CaseIterable & RawRepresentable
{
    var enumsObject: [String: T.RawValue] = [:];
    
    for enumData in Enum.allCases {
        let value = enumData.rawValue;
        enumsObject["\(enumData)"] = value;
    }
    
    return enumsObject;
}


print(enumToObj(Animal.self))
// ["CAT": "cat", "DOG": "dog", "BIRD": "bird"]

print(enumToObj(Car.self))
// ["AUDI": "audi", "BMW": "bmw"]

Using reduce(into:_:) this can also be written as

func enumToObj<T>(_ Enum:T.Type) -> [String: T.RawValue]
    where T: CaseIterable & RawRepresentable
{
    return Enum.allCases.reduce(into: [:]) { (enumsObject, enumData) in
        let value = enumData.rawValue;
        enumsObject["\(enumData)"] = value;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading