sorted function in Swift 2

前端 未结 5 634
心在旅途
心在旅途 2020-12-19 14:09

I\'m sorting an Array like this:

var users = [\"John\", \"Matt\", \"Mary\", \"Dani\", \"Steve\"]

func back (s1:String, s2:String) -> Bool
{
    return s1         


        
相关标签:
5条回答
  • 2020-12-19 14:15

    Another way is to use closure in a simple way:

    users.sort({a, b in a > b})
    
    0 讨论(0)
  • 2020-12-19 14:20

    Another way to use closure is:

    var numbers = [2,4,34,6,33,1,67,20]
    
    
    var numbersSorted = numbers.sort( { (first, second ) -> Bool in
    
        return first < second
    })
    
    0 讨论(0)
  • 2020-12-19 14:21

    In swift 2.2 there are multiple ways we can use closures with sort function as follows.

    Consider the array

    var names:[String] = ["aaa", "ffffd", "rrr", "bbb"];
    

    The different options for sorting the array with swift closures are as added

    Option 1

    // In line with default closure format.
    names = names.sort( { (s1: String, s2: String) -> Bool in return s1 < s2 })
    print(names)
    

    Option 2

    // Omitted args types
    names = names.sort( { s1, s2 in return s1 > s2 } )
    print(names)
    

    Option 3

    // Omitted args types and return keyword as well
    names = names.sort( { s1, s2 in s1 < s2 } )
    print(names)
    

    Option 4

    // Shorthand Argument Names(with $ symbol)
    // Omitted the arguments area completely.
    names = names.sort( { $0 < $1 } )
    print(names)
    

    Option 5

    This is the most simple way to use closure in sort function.

    // With Operator Functions
    names = names.sort(>)
    print(names)
    
    0 讨论(0)
  • 2020-12-19 14:27
    var array = [1, 5, 3, 2, 4] 
    

    Swift 2.3

    let sortedArray = array.sort()
    

    Swift 3.0

    let sortedArray = array.sorted()
    
    0 讨论(0)
  • 2020-12-19 14:35

    Follow what the error message is telling you, and call sort on the collection:

    users.sort(back)
    

    Note that in Swift 2, sorted is now sort and the old sort is now sortInPlace, and both are to be called on the array itself (they were previously global functions).

    Be careful, this has changed again in Swift 3, where sort is the mutating method, and sorted is the one returning a new array.

    0 讨论(0)
提交回复
热议问题