神秘的“通话中的额外论点"数组扩展方法中的错误 [英] Mysterious "extra argument in call" error in Array extension method

查看:65
本文介绍了神秘的“通话中的额外论点"数组扩展方法中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它将编译:

extension Array {
    func chunked(by chunkSize:Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<[$0 + chunkSize, self.count].min()!])
        }
    }
}

这不是(用全局min()函数代替数组min()方法):

This doesn't (substituting the global min() function for the array min() method):

extension Array {
    func chunked(by chunkSize:Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0..<min($0 + chunkSize, self.count)]) // error
        }
    }
}

编译错误指向self.count并显示调用中的额外参数".

The compile error points to self.count and says "extra argument in call".

但是如果我们不在Array扩展中,那么第二种形式就可以了:

But if we're not in an Array extension, the second formulation is fine:

let arr = [1,2,3,4,5,6]
let chunkSize = 2
let chunks = stride(from: 0, to: arr.count, by: chunkSize).map {
    Array(arr[$0..<min($0 + chunkSize, arr.count)]) // fine
}

那么,第二个公式中的编译错误实际上是Swift编译器错误吗?如果不是,那么第二种说法有什么问题?我知道调用中的额外参数"通常对来自Swift编译器的问题的描述不佳,但是什么是 real 问题呢?为什么在Array扩展名内会触发此错误?

So, is the compile error in the second formulation actually a Swift compiler bug? If not, what's wrong with the second formulation? I'm aware that "extra argument in call" is often a poor description of the problem coming from the Swift compiler, but then what's the real problem? Why does being inside an Array extension trigger this error?

推荐答案

编译器正在将仅使用一个参数的Swift.Array.min(by:)与您打算使用的全局函数Swift.min(_:_:)进行合并.

The compiler is conflating Swift.Array.min(by:), which only takes a single argument, with the global function Swift.min(_:_:) that you're intending to use.

通过为其全局名称加上模块名称(Swift)来明确限定全局功能可以解决此问题:

Explicitly qualifying the global function by prefixing it with its module name (Swift) resolves the issue:

extension Array {
    func chunked(by chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map {
            Array(self[$0 ..< Swift.min($0 + chunkSize, self.count)]) // fixed
        }
    }
}

这篇关于神秘的“通话中的额外论点"数组扩展方法中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆