2016-08-18 20 views
0

我很迷惑約swif2 AnyGenerator和GeneratorOfOne.When我寫了下面的代碼Swift2 GeneratorOfOne.next()出現錯誤:無法使用不可變值可變成員:函數調用返回不可變的值

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

的編譯是正確的。 但是,如果沒有使用AnyGenerator

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

代碼無法compile.The誤差是

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

+0

請參閱[這篇博客文章](https://airspeedvelocity.net/2014/07/28/collection-and-sequence-helpers/)瞭解'GeneratorOfOne'的一些細節。 – dfri

回答

1

你正在接受的錯誤,因爲nextmutating方法,這需要對一個變量被稱爲( var)。在常量上調用它(let)將不起作用。

這編譯:

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

同樣next調用工作在AnyGenerator因爲在該結構的方法不是mutating一個。下面硒在討論兩個結構的定義提取物:

public struct AnyGenerator<Element> : GeneratorType { 

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

    public func next() -> Element? 
} 

public struct GeneratorOfOne<Element> : GeneratorType, SequenceType { 

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

    public mutating func next() -> Element? 
} 
+0

感謝您的幫助。 – matthew

0

根據docsnext()是變異的功能。 你必須保持var引用它:

var generator = GeneratorOfOne([1,2,3]) 
let next = generator.next() 
相關問題