使用for循环使类可迭代?
我有一个自定义的类:
class MyArrayClass { ... }
这个类是一个自定义列表实现。
我想要做到以下几点:
var arr:MyArrayClass = MyArrayClass() arr.append("first") arr.append("second") arr.append("third") for entry in arr { println("entry: \(entry)") }
编辑:我想要迭代的类是JavaUtilArrayList它使用这个类IOSObjectArray 。
哪个协议必须由我的类确认,以便它在for循环中工作?
你可以使用NSFastGenerator
更快:
extension MyArrayClass: SequenceType { public func generate() -> NSFastGenerator { return NSFastGenerator(self) } }
你应该看看这个确切的话题的博客文章。 我会在这里写一个总结:
当你写:
// mySequence is a type that conforms to the SequenceType protocol. for x in mySequence { // iterations here }
Swift将其转换为:
var __g: Generator = mySequence.generate() while let x = __g.next() { // iterations here }
因此,为了能够通过你的自定义types来枚举,你需要让你的类实现SequenceType
协议。 看下面的SequenceType
协议,你可以看到你只需要实现一个返回符合GeneratorType
协议的对象的方法( GeneratorType
包含在博客文章中)。
protocol SequenceType : _Sequence_Type { typealias Generator : GeneratorType func generate() -> Generator }
下面是一个如何在for
循环中使MyArrayClass
可用的例子:
class MyArrayClass { var array: [String] = [] func append(str: String) { array.append(str) } } extension MyArrayClass : SequenceType { // IndexingGenerator conforms to the GeneratorType protocol. func generate() -> IndexingGenerator<Array<String>> { // Because Array already conforms to SequenceType, // you can just return the Generator created by your array. return array.generate() } }
现在在实践中使用这个:
let arr = MyArrayClass() arr.append("first") arr.append("second") arr.append("third") for x in arr { println(x) } // Prints: // First // Second // Third
我希望能回答你的问题。