为什么同样的方法在斯威夫特阵列扩展内部时失败? [英] Why does the same method fail when inside an Array extension in Swift?

查看:122
本文介绍了为什么同样的方法在斯威夫特阵列扩展内部时失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打电话的时候得到奇怪的行为排序()从阵列扩展中,例如这种方法:

I'm getting strange behavior when trying to call sort() from within an Array extension, e.g this method:

func test() {
    let a = [1,2,3]
    sort(a) { x, y in x < y }
}

作品自身,但没有当它是一个阵列扩展中:

extension Array {
    func test() {
        let a = [1,2,3]
        sort(a) { x, y in x < y }
    }
}

这是一个生成错误,与失败:

It's a build error, failing with:

在调用额外的参数

奇怪的是同样的方法可以作为一个字符串扩展:

Curiously the same method works as a String extension:

extension String {
    func test() {
        let a = [1,2,3]
        sort(a) { x, y in x < y }
    }
}

我为什么不能叫排序()从阵列扩展中?

推荐答案

由于阵列有一个名为方法排序

Because Array has a method called sort of its own, which is of the form sort(isOrderedBefore: (T, T) -> Bool)

所以,当你调用排序 阵列的范围内,你实际上指的是版本,而不是全球排序功能。

So, when you call sort inside the scope of Array, you are actually referring to that version instead of the global sort function.

感谢这个答案在我的问题,我发现,你可以确保你调用排序版本在使用雨燕的默认名称空间,雨燕在全球范围内。因此,全球的版本通过 Swift.sort 是可访问的。

Thanks to this answer in a question of mine, I found that you can make sure you're calling the sort version in the global scope by using Swift's default namespace, Swift. So, the global version is accessible via Swift.sort.

这篇关于为什么同样的方法在斯威夫特阵列扩展内部时失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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