Why does the same method fail when inside an Array extension in Swift?

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

Works on its own, but fails when its inside an Array extension:

  • “Unrecognized selector sent to instance” in swift
  • Swift generic superclass' init not accessible when constructing its subclass
  • local native-iOS time-hack proof background count-down timer
  • Error when compiling a static library using Swift “unknown option character `X' in: -Xlinker”
  • Stack View ScaleAspectFit Mask Resize in Swift
  • Determinate finish loading website in webView with Swift in Xcode
  • extension Array {
        func test() {
            let a = [1,2,3]
            sort(a) { x, y in x < y }
        }
    }
    

    It’s a build error, failing with:

    Extra argument in call

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

    Why can’t I call sort() from within an Array extension?

    Solutions Collect From Internet About “Why does the same method fail when inside an Array extension in Swift?”

    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.

    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.