Решение для этого ниже для Xcode 10 и Swift 4.2 и выше.
Шаг 1: Создать протокол EnumIterable.
protocol EnumIterable: RawRepresentable, CaseIterable {
var indexValue: Int { get }
}
extension EnumIterable where Self.RawValue: Equatable {
var indexValue: Int {
var index = -1
let cases = Self.allCases as? [Self] ?? []
for (caseIndex, caseItem) in cases.enumerated() {
if caseItem.rawValue == self.rawValue {
index = caseIndex
break
}
}
return index
}
}
Шаг2: Расширение протокола EnumIterator на ваши перечисления.
enum Colors: String, EnumIterable {
case red = "Red"
case yellow = "Yellow"
case blue = "Blue"
case green = "Green"
}
Шаг 3: Используйте свойство indexValue, как при использовании hashValue.
Colors.red.indexValue
Colors.yellow.indexValue
Colors.blue.indexValue
Colors.green.indexValue
ПримерВывод на печать и вывод
print("Index Value: \(Colors.red.indexValue), Raw Value: \(Colors.red.rawValue), Hash Value: \(Colors.red.hashValue)")
Вывод: «Значение индекса: 0, Необработанное значение: Красный, Значение хеш-функции: 1593214705812839748»
print("Index Value: \(Colors.yellow.indexValue), Raw Value: \(Colors.yellow.rawValue), Hash Value: \(Colors.yellow.hashValue)")
Вывод: «Значение индекса: 1, Сырое значение: Желтый, Значение хэша: -6836447220368660818 "
print("Index Value: \(Colors.blue.indexValue), Raw Value: \(Colors.blue.rawValue), Hash Value: \(Colors.blue.hashValue)")
Выход:" Значение индекса: 2, Сырое значение: Синий, Значение хэша: -8548080225654293616 "
print("Index Value: \(Colors.green.indexValue), Raw Value: \(Colors.green.rawValue), Hash Value: \(Colors.green.hashValue)")
Выход: "Значение индекса: 3, Сырое значение: Зеленый, Значение хэша: 6055121617320138804"