【问题标题】:Mysterious "extra argument in call" error in Array extension method [duplicate]数组扩展方法中神秘的“调用中的额外参数”错误[重复]
【发布时间】:2017-03-07 00:56:57
【问题描述】:

这样编译:

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() 方法):

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 并显示“调用中的额外参数”。

但是如果我们不在一个数组扩展中,第二个公式就可以了:

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 编译器的问题,但是 真正的 问题是什么?为什么在 Array 扩展中会触发此错误?

【问题讨论】:

  • 对于the problem described here 来说这是一个糟糕的错误——尽管在 Swift 3.1 中,诊断大大改进为“使用'min'是指实例方法'min (by:)' 而不是模块 'Swift' 中的全局函数 'min'"
  • @Hamish 你的评论让我看到了一些我以前从未见过的 SO 界面,提供让我自我标记这个作为副本。酷。

标签: arrays swift3 extension-methods


【解决方案1】:

编译器将Swift.Array.min(by:)(仅接受一个参数)与您打算使用的全局函数Swift.min(_:_:) 混为一谈。

通过在全局函数前面加上其模块名称 (Swift) 来明确限定全局函数可解决问题:

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
        }
    }
}

【讨论】:

  • LOL 所以答案实际上隐含在问题的第一个公式中。这实际上与我在这里的回答相似:stackoverflow.com/a/34107042/341994 哦,具有讽刺意味!
  • 我是不是……我刚刚回答了 Swift 霸主@matt 的问题?! :O
  • 我不知道,但这是一个完美的答案!清晰、简洁,包括解决方案。不能再问了。
猜你喜欢
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-27
  • 1970-01-01
  • 2017-02-02
相关资源
最近更新 更多