How to sort an array in Swift

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

I want the Swift version of this code:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
相关标签:
8条回答
  • 2020-12-13 05:08

    In Swift-

    let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
    let sortedStudents = students.sorted()
    print(sortedStudents)
    // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
    

    To sort the elements of your sequence in descending order, pass the greater-than operator (>) to the sorted(isOrderedBefore:) method.

    let descendingStudents = students.sorted(isOrderedBefore: >)
    print(descendingStudents)
    // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
    
    0 讨论(0)
  • 2020-12-13 05:11
    var names = [ "Alpha", "alpha", "bravo"]
    var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
    

    Update: Providing explanation as per recommendation of a fellow SO user.

    Unlike ObjC, in Swift you have sorted() (and sort()) method that takes a closure that you supply that returns a Boolean value to indicate whether one element should be before (true) or after (false) another element. The $0 and $1 are the elements to compare. I used the localizedCaseInsensitiveCompare to get the result you are looking for. Now, localizedCaseInsensitiveCompare returns the type of ordering, so I needed to modify it to return the appropriate bool value.

    Update for Swift 2: sorted and sort were replaced by sort and sortInPlace

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