Question: Sort an unsorted array with Closures

Question

Sort an unsorted array with Closures

Answers 1
Added at 2016-12-31 17:12
Tags
Question
let unsortedArray = [98,23,643,678,2,568,1,234,556,4] {
    (first:Int , second:Int) -> Bool in 

    if first < second {
        return true
    } else{
        return false
    }
}

Above code is to sort an unsorted array with Swift 2 and Xcode 7.3.

I want to know how can i print the result?

Answers to

Sort an unsorted array with Closures

nr: #1 dodano: 2016-12-31 22:12

The syntax is:

let unsortedArray = [98, 23, 643, 678, 2, 568, 1, 234, 556, 4]
let sortedArray = unsortedArray.sort() { (first: Int, second: Int) -> Bool in
    if first < second {
        return true
    } else {
        return false
    }
}

print("\(sortedArray)")

Note, in Swift 2.3 that's sort, but in Swift 3, it is now called sorted.


By the way, this can be simplified:

let sortedArray = unsortedArray.sort { (first: Int, second: Int) -> Bool in
    return first < second
}

Or, further simplified to use anonymous closure arguments:

let sortedArray = unsortedArray.sort {
    return $0 < $1
}

Which because there is a single expression inside the closure, you can further simply to:

let sortedArray = unsortedArray.sort { $0 < $1 }

Or, further simplified to:

let sortedArray = unsortedArray.sort(<)

Or, because the elements of the array, Int types, conform to Comparable, you can omit the closure entirely and use a different sort method that takes no parameters at all:

let sortedArray = unsortedArray.sort()

Note, this requires that the elements of the array have:

The less-than operator (func <) defined in the Comparable conformance is a strict weak ordering over the elements in self.

Source Show
◀ Wstecz