Cezar
Cezar

Reputation: 56362

Calling a global function which has the same name as a member function

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).

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.

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, ::

Upvotes: 26

Views: 4750

Answers (2)

Yawar
Yawar

Reputation: 11627

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.

Upvotes: 38

shucao
shucao

Reputation: 2242

Wrap the global sort, for example,

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

Upvotes: -1

Related Questions