Sorting of an array alphabetically in swift

后端 未结 7 1300
感动是毒
感动是毒 2020-12-23 14:03

I am new to swift.I am trying one sample app in which I need to implement the sorting of an array in alphabetical order.I getting the json data and I am adding the titles in

相关标签:
7条回答
  • 2020-12-23 14:28

    Swift4

    var names = [ "Alpha", "alpha", "bravo", "beta"]
    var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
    print(sortedNames) //Logs ["Alpha", "alpha","beta", "bravo"]
    
    0 讨论(0)
  • 2020-12-23 14:30

    Swift 4(working code)

    JSON response -> Stored in aryNameList

    "DATA": [
    {
            email = "iosworker@gmail.com";
            firstname = Harvey
    },
    {
            email = "poonam@openxcell.com";
            firstname = poonam
    },
    {
            email = "t@t.com";
            firstname = rahul
    },
    {
            email = "android.testapps@gmail.com";
            firstname = Chulbulx
    },
    {
            email = "t@t2.com";
            firstname = rahul
    },
    {
            email = "jaystevens32@gmail.com";
            firstname = Jay
    },
    {
            email = "royronald47@gmail.com";
            firstname = Roy
    },
    {
            email = "regmanjones@hotmail.com";
            firstname = Regan
    },
    {
            email = "jd@gmail.com";
            firstname = Jaydip
    }
    ]
    

    Code

        self.aryNameList = self.aryNameList.sorted(by: { (Obj1, Obj2) -> Bool in
           let Obj1_Name = Obj1.firstname ?? ""
           let Obj2_Name = Obj2.firstname ?? ""
           return (Obj1_Name.localizedCaseInsensitiveCompare(Obj2_Name) == .orderedAscending)
        })
    

    working every case (for ex: lowerCase, upperCase..)

    0 讨论(0)
  • 2020-12-23 14:32

    Try this one

    var names = [ "Alpha", "alpha", "bravo"]
    var sortedNames = names.sort { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
    print(sortedNames) //Logs ["Alpha", "alpha", "bravo"]
    
    0 讨论(0)
  • 2020-12-23 14:38

    For an array of objects:

    items = items.sorted(by: { (item1, item2) -> Bool in
            return item1.product.name.compare(item2.product.name) == ComparisonResult.orderedAscending
        })
    
    0 讨论(0)
  • 2020-12-23 14:42

    Swift 3 solution:

    let yourStringArray = [ "beTA", "ALPha", "Beta", "Alpha"]
    var sortedArray = yourStringArray.sorted()
    // Result will be ["ALPha", "Alpha", "Beta", "beTA"]
    

    Creds to jjatie

    0 讨论(0)
  • 2020-12-23 14:46

    Use this simple code of line to sort ur array

     let sortedNames = names.sort { $0.name < $1.name }
    

    For Swift 4 you can use only this

    let sortedNames = names.sorted(by: <)
    
    0 讨论(0)
提交回复
热议问题