在swift中根据参数对对象进行排序

时间:2018-01-16 10:57:07

标签: swift

我有数组对象,我想根据参数对对象数组进行排序。

class User {
    var firstName, lastName, userName: String?
    var id: UUID? 
}

我有userObject数组。我想根据用户userName对用户进行排序,并按适当顺序返回userObjects数组。

userArray = [(Shyam,M,ShayamM,1),(Amar,S,AmarS,3)),(Prema,A,PremaA,2))]     userArray = userArray?.sorted(by:{$ 0.name!< $ 1.name!})

我想要这样的输出: userArray = [(Amar,S,AmarS,3)),(Prema,A,PremaA,2)),(Shyam,M,ShayamM,1)]

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

    var userArray = [User("Shyam", "M", "ShayamM", 1), User("Amar", "S", "AmarS", 3), User("Prema", "A", "PremaA", 2)]
    userArray.sort { (user1, user2) -> Bool in
        if let username1 = user1.userName, let username2 = user2.userName
        {
            return username1 < username2
        }
        return false
    }