在Swift中检查NSCFBoolean?

时间:2018-08-22 18:20:46

标签: ios swift xcode boolean

我正在制作iOS中的待办事项列表应用程序。我将用户的任务存储在Firebase中。任务完成后,我将更新数据库中的值。读回该值时,由于我之前遇到的一些错误,我对其进行了Bool,NSNumber和String测试。使用type(of :),该值被读取为“ __NSCFBoolean”,并且我在switch语句中的默认情况正在运行。我该如何测试这种类型?

很抱歉,如果这是一个重复的问题,我只能在Objective-C中找到带有NSCFBoolean的帖子。

这是我当前的代码:

func observeForChildAdded(tableView: UITableView, snapshot: DataSnapshot) {
    let snapshotValue = snapshot.value as! Dictionary<String,Any>
    let taskIsCompleted = getIsCompletedSnapshotValue(snapshotValue: snapshotValue)
… 
}

func getIsCompletedSnapshotValue(snapshotValue: Dictionary<String,Any>) -> Bool {
    print(“Complete value : \(snapshotValue[“isCompleted”]!) : \(type(of: snapshotValue[“isCompleted”]!))”)

    if let isCompValue = snapshotValue[“isCompleted”]! as? Bool {
        return isCompValue
    } else if let isCompValue = snapshotValue[“isCompleted”]! as? Int {
        return (isCompValue == 1)
    } else if let isCompValue = snapshotValue[“isCompleted”]! as? String {
        return (isCompValue == “true”)
    }
    return false
}
每当将子级添加到Firebase数据库时,就会调用

observeForChildAdded()。 它打印: 完整值:0:__ NSCFBoolean

1 个答案:

答案 0 :(得分:2)

这是一个独立的示例,展示了__NSCFBoolean可以强制转换为BoolInt,但不能强制转换为String

let snapshotValue: [String : Any] = ["isCompleted": false as CFBoolean, "isCompleted2": true as CFBoolean]

print("snapshotValue[\"isCompleted\"] is of type \(type(of: snapshotValue["isCompleted"]!))")
print("snapshotValue[\"isCompleted2\"] is of type \(type(of: snapshotValue["isCompleted2"]!))")

if let b1 = snapshotValue["isCompleted"] as? Bool {
    print("isCompleted is \(b1)")
} else {
    print("isCompleted is not a Bool")
}

if let b2 = snapshotValue["isCompleted2"] as? Bool {
    print("isCompleted2 is \(b2)")
} else {
    print("isCompleted2 is not a Bool")
}

if let i1 = snapshotValue["isCompleted"] as? Int {
    print("isCompleted is \(i1)")
} else {
    print("isCompleted is not an Int")
}

if let i2 = snapshotValue["isCompleted2"] as? Int {
    print("isCompleted2 is \(i2)")
} else {
    print("isCompleted2 is not an Int")
}

if let s1 = snapshotValue["isCompleted"] as? String {
    print("isCompleted is \(s1)")
} else {
    print("isCompleted is not a String")
}

if let s2 = snapshotValue["isCompleted2"] as? String {
    print("isCompleted2 is \(s2)")
} else {
    print("isCompleted2 is not a String")
}

// Testing with a switch
switch snapshotValue["isCompleted"] {
case let b as Bool:
    print("it is a Bool with value \(b)")
case let i as Int:
    print("it is an Int with value \(i)")
case let s as String:
    print("it is a String with value \(s)")
default:
    print("is is something else")
}

输出

snapshotValue["isCompleted"] is of type __NSCFBoolean
snapshotValue["isCompleted2"] is of type __NSCFBoolean
isCompleted is false
isCompleted2 is true
isCompleted is 0
isCompleted2 is 1
isCompleted is not a String
isCompleted2 is not a String
it is a Bool with value false