According to the documentation:
init(_ s: S) where Element == S.Element, S : Sequence
Creates an array containing the elements of a sequence.
struct Test: IteratorProtocol, Sequence {
let id: Int
init(_ id: Int) {
self.id = id
}
mutating func next() -> Test? {
id < 10 ? Test(id + 1) : nil
}
}
let test = Test(5)
let arr = Array(test)
It compiles. And doesn't even throw any runtime errors.
But instead of getting the array [5, 6, 7, 8, 9] as a result, I get an infinite loop! next()
is called infinitely many times.
I thought that nil
in next()
is a natural indicator of the end of sequence. But apparently it's not.