我正在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:\u NSCFBoolean
最佳答案
下面是一个独立的示例,它演示了__NSCFBoolean
可以被转换为Bool
或Int
,但不能被转换为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