How to sort an array in Swift

后端 未结 8 1925
陌清茗
陌清茗 2020-12-13 04:06

I want the Swift version of this code:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 05:06

    Most efficient way of sorting in SWIFT

    The use of Operator Overloading is the most efficient way to sort Strings in Swift language.

    // OPERATOR OVERLOADING
    let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
    var sortedNames = sorted(names, <)
    var reverseOrder = sorted(names, >)
    

    In above code > and < operators are overloaded in Swift to sort Strings.

    I have test the code in Playground and conclude that when we use operator overloading it is best for sorting Strings.

    Copy below to Playground.

    let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
    
    var reversed = sorted (names,
        // This is a closure
        { (s1 : String, s2 : String) -> Bool in
            return s1 > s2
        }
    )
    println(reversed)
    
    var reverseOrder = sorted(names, {s1, s2 in s1 > s2})
    
    var reverseOrder2 = sorted(names, { $0 > $1} )
    
    // OPERATOR OVERLOADING
    var reverseOrder3 = sorted(names, >)
    

    The conclusion from Playground:

    enter image description here

    From above image you can see that all other ways needs to enumerate loops for sorting 5 strings. Where as when we use Operator overloading it does not required to enumerate loop to sort strings.

    Referenced from Swift documentation

提交回复
热议问题