在swift中通过array.count对对象进行排序

时间:2015-10-08 16:14:36

标签: arrays swift class sorting object

我有一类用户和另一个用于设备:

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个用户附加了不同数量的设备,我想根据他们拥有的设备数量对它们进行排序。我已经尝试了很多,并没有设法做到这一点..

2 个答案:

答案 0 :(得分:1)

试试这个(按升序排序):

userArray = userArray.sort({ $0.devices.count < $1.devices.count })

答案 1 :(得分:0)

.sort是你的朋友。

减少问题:

struct User {
    var name: String
    var numberOfDevices: Int
}

var users = [User]()
users.append(User(name: "Mark", numberOfDevices: 4))
users.append(User(name: "Tom", numberOfDevices: 55))
users.append(User(name: "Jerry", numberOfDevices: 10))
users.append(User(name: "Rex", numberOfDevices: -5))

var sortedUsers = users.sort({ $0.numberOfDevices > $1.numberOfDevices })
print(sortedUsers)