【发布时间】:2017-05-12 04:17:17
【问题描述】:
我有一个简单的枚举,我想对其进行迭代。为此,我采用了 Sequence 和 IteratorProtocol,如下面的代码所示。顺便说一句,这可以在 Xcode 8 中复制/粘贴到 Playground。
import UIKit
enum Sections: Int {
case Section0 = 0
case Section1
case Section2
}
extension Sections : Sequence {
func makeIterator() -> SectionsGenerator {
return SectionsGenerator()
}
struct SectionsGenerator: IteratorProtocol {
var currentSection = 0
mutating func next() -> Sections? {
guard let item = Sections(rawValue:currentSection) else {
return nil
}
currentSection += 1
return item
}
}
}
for section in Sections {
print(section)
}
但是 for-in 循环会生成错误消息“Type 'Sections.Type' does not conform to protocol 'Sequence'”。 协议一致性在我的扩展中;那么,这段代码有什么问题呢?
我知道还有其他方法可以做到这一点,但我想了解这种方法有什么问题。
谢谢。
【问题讨论】:
-
这里有很多答案可以解决你的问题(问题是关于字符串类型,但大多数答案都适用于任何类型):stackoverflow.com/questions/24007461/…
-
我有一个答案你可以参考这里stackoverflow.com/a/48960126/5372480
标签: swift enums sequence enumeration