matthew matthew - 3 months ago 19
Swift Question

Swift2 GeneratorOfOne.next() occur error: cannot use mutating member on immutable value: function call returns immutable value

I am very confuse about swif2 AnyGenerator and GeneratorOfOne.When I write the following code

AnyGenerator(GeneratorOfOne([1,2,3])).next()


The compile is correct.
But without use AnyGenerator

GeneratorOfOne([1,2,3]).next()


The code can't compile.The error is


cannot use mutating member on immutable value: function call returns
immutable value.

Answer

You are receiving the error because next is a mutating method, which needs to be called on a variable.

This compiles:

var generator = GeneratorOfOne([1,2,3])
generator.next()

The same next call works on AnyGenerator because on that struct the method is not a mutating one. Se below extracts from the definitions of the two structs in discussion:

public struct AnyGenerator<Element> : GeneratorType {

.................................

    public func next() -> Element?
}

public struct GeneratorOfOne<Element> : GeneratorType, SequenceType {

.................................

    public mutating func next() -> Element?
}