Function enum parameter type
Solution 1:
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;
}
}