我有数组对象,我想根据参数对对象数组进行排序。
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)]
答案 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
}