0

I saw this answer How to enumerate an enum with String type?

Now I'm trying to create method that will return array of strings with the raw values of the enum.

So I did :

class func enumValues<T>(from array: AnyIterator<T>) -> [T] where T:RawRepresentable, T:Hashable {
    var tempArray = [T]()
    for item in array{
        tempArray.append(item.rawValue)
    }
    return tempArray
}

But, i get this error :

Argument type 'T.RawValue' does not conform to expected type 'Hashable'

Argument type 'T.RawValue' does not conform to expected type 'RawRepresentable'

How can i fix this problem? thanks

Community
  • 1
  • 1
Maor
  • 3,340
  • 3
  • 29
  • 38

2 Answers2

1

You want to return an array with the raw values of the array elements, so the return type should be T.RawValue (and the constraint T:Hashable is not needed):

func enumValues<T>(from array: AnyIterator<T>) -> [T.RawValue] where T: RawRepresentable {
    var tempArray: [T.RawValue] = []
    for item in array{
        tempArray.append(item.rawValue)
    }
    return tempArray
}

which can be simplified to

func enumValues<T>(from array: AnyIterator<T>) -> [T.RawValue] where T: RawRepresentable {
    return array.map { $0.rawValue }
}

or more generally for any sequence of raw-representables:

func enumValues<S: Sequence>(from sequence: S) -> [S.Iterator.Element.RawValue]
    where S.Iterator.Element: RawRepresentable {

    return sequence.map { $0.rawValue }
}

On the other hand one may ask if this is worth a separate function at all, since you can call map { $0.rawValue } directly on the given iterator/sequence/array.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

To return array of strings with the raw values of the enum all you need to do is to conform to CaseIterable.

enum WeekDay: String, CaseIterable {
    case monday, tuesday, wednesday, thursday, friday
}

let arrayOfRawValues = WeekDay.allCases.map(\.rawValue)
Paul B
  • 3,989
  • 33
  • 46