2017-06-06 46 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