在领域中对Int进行查询时值无效

时间:2018-09-12 09:47:45

标签: swift int realm

我有一个这样的领域声明:

@objc dynamic var roomId = UUID().uuidString
@objc dynamic var roomName = ""
@objc dynamic var roomType = ""
@objc dynamic var floor = 1
@objc dynamic var placeId : String?

我正在尝试使用此功能从领域DB获取特定位置特定楼层的所有房间的查询:

static func getAllRoomNamesAndTypesForQuery (placeName: String? ,room : String? , floor : Int?) -> [[String]] {
    var result : [[String]] = [[]]
    if placeName != nil , floor != nil {
    let placeId = Places.specificPlaceQueries(placeName: placeName)[0] as! String
    let allRooms = Users.realm.objects(Rooms.self).filter("placeId == '\(placeId)' AND floor == '\(floor!)'")
    var roomNames = [""]
    var roomTypes = [""]
    for number in 0..<allRooms.count {
        roomNames.append(allRooms[number].roomName)
        roomTypes.append(allRooms[number].roomType)
    }

    let sortedRoomNames = roomNames.sorted()
    let sortedRoomTypes = roomTypes.sorted()

    result = [sortedRoomNames , sortedRoomTypes]
    }
    return result

}

但它一直向我显示以下奇怪的错误

  

类型为'floor'的属性类型为int的预期对象   “房间”,但收到了:1

我不知道它如何拒绝1作为Int?有人知道这里的问题在哪里吗?

3 个答案:

答案 0 :(得分:1)

创建NSPredicate时不应使用字符串插值,因为即使支持,也很容易弄乱谓词格式。只需使用%@即可将变量值替换为谓词。

let allRooms = Users.realm.objects(Rooms.self).filter("placeId == %@ AND floor == %@",placeId, floor)

对代码进行了一些进一步的改进:不要使用nil检查,而是强制展开,在使用Optionals时使用可选绑定。

if let placeName = placeName , let floor = floor {

创建数组时也不要向数组添加初始值,而不是var roomNames = [""]var roomTypes = [""]

var roomNames = [String]()
var roomTypes = [String]()

答案 1 :(得分:0)

你能尝试

let allRooms = Users.realm.objects(Rooms.self).filter { 
   $0.placeId == placeId  
   && $0.floor == floor 
}

答案 2 :(得分:0)

第一页:

设置

var roomNames = [""];
var roomTypes = [""];

对此

var roomNames = [String]()
var roomTypes = [String]()