Here is the code that works fine and this is implementation of the Iterator pattern:
struct Candies {
let candies: [String]
}
extension Candies: Sequence {
func makeIterator() -> CandiesIterator {
return CandiesIterator(sequence: candies, current: 0)
}
}
struct CandiesIterator: IteratorProtocol {
let sequence: [String]
var current = 0
mutating func next() -> String? {
defer { current += 1 }
return sequence.count > current ? sequence[current] : nil
}
}
Here is the code that I thought to be as a generic variation of the code above but I have two errors (see below the code):
struct Whatevers<T> {
let whatevers: [T]
}
extension Whatevers: Sequence {
func makeIterator() -> Whatevers<T>.Iterator {
return WhateversIterator(sequence: whatevers, current: 0)
}
}
struct WhateversIterator<T>: IteratorProtocol {
let sequence: [T]
var current = 0
mutating func next() -> WhateversIterator.Element? {
defer { current += 1 }
return sequence.count > current ? sequence[current] : nil
}
}
error: MyPlayground.playground:854:1: error: type 'Whatevers' does not conform to protocol 'Sequence' extension Whatevers: Sequence { ^
error: MyPlayground.playground:861:8: error: type 'WhateversIterator' does not conform to protocol 'IteratorProtocol' struct WhateversIterator: IteratorProtocol {
Can someone explain what is incorrect in this code. And how can I make it work?
Aucun commentaire:
Enregistrer un commentaire