我有一类用户和另一类设备:
class User {
var userId: Int
var userName: String
var location: String
var devices = [Device]()
init(user_id: Int, userName: String, location: String, devices: [Device]){
userId = user_id
self.userName = userName
self.location = location
self.devices = devices
}}
class Device{
var deviceId : Int
var type: deviceType
var operating_system: operatingSystem
var userId: Int
var description: String
var inventoryNumber: String
init(device_id: Int, type: deviceType, operating_system : operatingSystem, userId:Int, description: String, inventory_num: String ){
self.userId = userId
deviceId = device_id
self.type = type
self.operating_system = operating_system
self.description=description
inventoryNumber = inventory_num
}}
我实例化了此类中的一些对象,我将在此处粘贴其中的一行:
var userArray = [User]()
var user1 = User(user_id: 1, userName: "John", location: "ClujNapoca", devices: [device1, device2])
我总共在数组中附加了 10 个用户,这些用户具有不同数量的设备,我想按他们拥有的设备数量对它们进行排序。我尝试了很多但没成功..
最佳答案
试试这个(按升序排序):
userArray = userArray.sort({ $0.devices.count < $1.devices.count })
关于arrays - 在 swift 中按 array.count 对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33020975/