2017-06-06 19 views
0

When I try the following code:雨燕3.1的錯誤:無法調用「步幅」型

extension Int{ 

    func hello(to end: Int, by step: Int, task: (Int) -> Void){ 

     for i in stride(from: 4, to: 8, by: 2) { 

      task(i) 
     } 
    } 
} 

And I get the error saying:

error: cannot invoke 'stride' with an argument list of type '(from: Int, to: Int, by: Int)' for i in stride(from: 4, to: 8, by: 2)

note: overloads for 'stride' exist with these partially matching parameter lists: (to: Self, by: Self.Stride), (through: Self, by: Self.Stride) for i in stride(from: 4, to: 8, by: 2)

的參數列表,我不爲什麼這種類型的錯誤發生

+0

我不能說爲什麼會出現此特定錯誤,但它工作正常,如果它不是在'Int'擴展。 – vadian

+0

比較https://stackoverflow.com/q/39602298/2976878。在你的具體情況中,問題在於編譯器看到了被聲明爲實例成員而不是全局函數(但現在不可用)的Swift 2'stride'方法。解決方案是相同的,用模塊名稱前綴呼叫以消除歧義。 – Hamish

回答

0

這有點棘手! :)

Int顯然聲明自己的stride方法(這就是爲什麼編譯器顯示你存在部分匹配的重載),但不知何故我無法訪問它們(編譯器說它們被標記爲不可用)。由於您處於Int分機中,因此在此情況下調用stride等同於self.stride。而Intstride方法沒有參數from:to:by:,所以它不能編譯。

您想具體參考全球性的stride方法。只要指定在其中定義的方法的模塊,即Swift

extension Int{ 

    func hello(to end: Int, by step: Int, task: (Int) -> Void){ 

     for i in Swift.stride(from: 4, to: 8, by: 2) { 

      task(i) 
     } 
    } 
} 
+0

謝謝,它適合我。 –

+0

@MenXuanCai如果您認爲我的回答可以回答您的問題,請考慮點擊該複選標記來接受它! – Sweeper