情景
有这么一个枚举类型
enum Animals:String {
case Frog = “Frog”
case Cat = “Cat”
case Dog = “Dog”
case Lion = “Lion”
case Tiger = “Tiger”
case Cattle = “Cattle”
}
现在我们需要把 Animals 的每个值都打印出来。
如果我们像遍历数组那么做
for animal in Animals {
print(animal.rawValue)
}
将得到错误提示
Type ‘Animals.Type’ does not conform to protocol ‘SequenceType’
解决方法
让我们来点小技巧化解这个尴尬的局面
enum Animals:String {
case Frog = “Frog”
case Cat = “Cat”
case Dog = “Dog”
case Lion = “Lion”
case Tiger = “Tiger”
case Cattle = “Cattle”
static let allValues = [Frog,Cat,Dog,Lion,Tiger,Cattle]
}
可能你已经猜到接下来该做些什么了
for animal in Animals.allValues {
print(animal.rawValue)
}