调用与成员函数同名的全局函数

时间:2022-03-26 08:26:18

The Array type in Swift has a member function called sort, with its signature being sort(isOrderedBefore: (T, T) -> Bool). This function differs from the global version of sort, which has the signature sort(array: T[], pred: (T, T) -> Bool).

Swift中的数组类型有一个名为sort的成员函数,其签名是sort(isOrderedBefore: (T, T) -> Bool)。这个函数与sort的全局版本不同,后者具有签名排序(数组:T[], pred: (T, T) -> Bool)。

If one extends an Array (see Why does the same method fail when inside an Array extension in Swift?), calling sort from inside the scope of the Array extension will naturally result in the local version being used.

如果扩展一个数组(参见在Swift中数组扩展中为什么相同的方法会失败?),那么从数组扩展范围内调用sort自然会导致使用本地版本。

Is it possible to explicitly call a function from an outer scope, or specifically from the global scope, even if its name coincides with that of a function from an inner scope?

是否可以从外部作用域或全局作用域显式地调用函数,即使它的名称与来自内部作用域的函数的名称一致?

This would be similar to the C++ scoping resolution operator, ::

这将类似于C+ scoping分辨率运算符:

2 个解决方案

#1


29  

Chris Lattner suggests qualifying the name of the global function with Swift's default namespace, Swift. So you should be able to access the global version using: Swift.sort.

Chris Lattner建议使用Swift的默认名称空间Swift来限定全局函数的名称。因此,您应该能够使用Swift.sort访问全局版本。

#2


0  

Wrap the global sort, for example,

包装全局排序,例如,

func my_sort<T>(arr: T[], pred: (T, T) -> Bool) -> T[] {
    return sort(arr, pred)
}

#1


29  

Chris Lattner suggests qualifying the name of the global function with Swift's default namespace, Swift. So you should be able to access the global version using: Swift.sort.

Chris Lattner建议使用Swift的默认名称空间Swift来限定全局函数的名称。因此,您应该能够使用Swift.sort访问全局版本。

#2


0  

Wrap the global sort, for example,

包装全局排序,例如,

func my_sort<T>(arr: T[], pred: (T, T) -> Bool) -> T[] {
    return sort(arr, pred)
}