Search code examples
iosswiftrealm

Find max of count items list


I am using Realm database on iOS and need to show the max count of office rooms in one building. I created models:

class Building: Object {
    dynamic var street: String!
    dynamic var number: Int!

    let offices = List<Office>()
}

class Office: Object {
    dynamic var square: Int!
    dynamic var number: Int!
    dynamic var floor: Int!

    let rooms = List<Room>()
}

class Room: Object {
    dynamic var width: Int!
    dynamic var height: Int!
}

How can I find max count of rooms in one building with help @count or @max? Is it possible?


Solution

  • You could sort the list of buildings by count of rooms and just take the first element:

    let soredOffices = soredOffices.sorted { $0.rooms.count > $1.rooms.count }
    if let maxNumberOfRooms = soredOffices.first {
        //use maxNumberOfRooms
    }