NSSortDescriptor in Swift

前端 未结 7 1641
长情又很酷
长情又很酷 2021-02-02 01:18

I am working on an iOS app and I have data stored in CoreData that I am loading into a UITableView. The data entities have an attribute called id which is a string

7条回答
  •  情歌与酒
    2021-02-02 01:56

    You can sort the collection of object with default sorted function as:

    e.g. your array of object is like

    data = [
        {
            name: "Naresh",
            dept: "CSC",
            id: 102
        },
        {
            name: "Rahul",
            dept: "CSC",
            id: 101
        },
        {
            name: "Amar",
            dept: "CSC",
            id: 100
        }
    ]
    
    //Comparing string key
    let sortByName = data.sorted { (model1, model2) -> Bool in
            return (model1.name.localizedCompare(model2.name) == ComparisonResult.orderedAscending)
    }
    
    /* The ComaprisonResult is default enum whose possible cases are: */
    public enum ComparisonResult : Int {
        case orderedAscending
        case orderedSame
        case orderedDescending
    }
    
    /*** SORTING ACCORDING TO NUMERICAL VALUE ***/
    
    //Comparing digit key including Int, Double, Float & all
    let sortByNumber = data.sorted { (model1, model2) -> Bool in
                return model1.id < model2.id
    }
    
    //You can use the shot form of automatic closure as:
    let sortByNumber = data.sorted { $0.id > $1.id }
    
    //In the autoclosure the $0 represent first parameter, $1 represent second parameter. The return statement is optional if closure or functions contains only single statement.
    

提交回复
热议问题