此代碼引發編譯器錯誤:“Argument type 'StrideTo' expected to be an instance of a class or class-constrained type”
extension Array {
func chunks(_ chunkSize: Int) -> [[Element]] {
let indexes = Array(stride(from: 0, to: count, by: chunkSize)) // This line won't compile
return [[Element]]()
}
}
但是,如果您在 Array 擴展之外使用非常相似的代碼:
let array = Array(stride(from: 0, to: 20, by: 4))
它給了我我所期望的,一個陣列[0, 4, 8, 12, 16]。
為什么在 Array 擴展的函式中創建臨時 Array 是非法的?它是否以某種方式呼叫stride()陣列上的實體方法?如果是這樣,有沒有辦法告訴編譯器我想呼叫全域stride()函式?
uj5u.com熱心網友回復:
這是一個錯誤:SR-13847 擴展中使用了錯誤的泛型:
出于某種原因,在擴展中呼叫初始化程式時,編譯器會嘗試匹配不相關的泛型。
在您的情況下,Array被解釋為Array<Element>. 作為一種解決方法,您可以顯式指定索引陣列的型別:
let indexes = Array<Int>(stride(from: 0, to: count, by: chunkSize))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418761.html
標籤:
