我有一个自定义类:
class MyArrayClass {
...
}
该类是一个自定义列表实现。
我想做以下事情:
var arr:MyArrayClass = MyArrayClass()
arr.append("first")
arr.append("second")
arr.append("third")
for entry in arr {
println("entry: \(entry)")
}
编辑:我想要使其可迭代的类是Java 实用程序 ArrayList https://gist.github.com/steffimueller/b48d64303f2579b86a5a它使用这个类IOS对象数组 https://gist.github.com/steffimueller/4df7775bc455a60e2148.
我的类必须确认哪个协议才能在 for in 循环中工作?
你应该看看this https://robots.thoughtbot.com/swift-sequences关于这个主题的博客文章。不过我会在这里写一个总结:
当你写:
// 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
}
因此,为了能够枚举您的自定义类型,您需要使您的类实现SequenceType
协议也是如此。看着SequenceType
下面的协议,您可以看到您只需要实现一个方法,该方法返回符合以下协议的对象GeneratorType
协议 (GeneratorType
博客文章中有介绍)。
protocol SequenceType : _Sequence_Type {
typealias Generator : GeneratorType
func generate() -> Generator
}
这是如何制作的示例MyArrayClass
可用于for
loop:
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
我希望这能回答你的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)