gpt4 book ai didi

swift - swift 根据对象的参数对对象进行排序

转载 作者:行者123 更新时间:2023-11-28 07:55:21 27 4
gpt4 key购买 nike

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

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)]

最佳答案

你可以这样做:

    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
}

关于swift - swift 根据对象的参数对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48279610/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com