sorted function in Swift 2

前端 未结 5 650
心在旅途
心在旅途 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: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)
    

提交回复
热议问题