if let action = self.info?["action"] {
switch action as! String {
....
}
} else {...}在本例中,"action“始终作为键存在于self.info中。
一旦执行第二行代码,我就会得到:
Could not cast value of type 'NSNull' (0x1b7f59128) to 'NSString' (0x1b7f8ae8).你知道动作是如何被NSNull的吗,即使我把它解开了?我甚至尝试过"if action != nil",但它仍然以某种方式滑过并导致SIGABRT。
发布于 2017-06-28 23:53:25
NSNull是一个特殊的值,通常由JSON处理产生。它与nil值有很大的不同。而且您不能将对象从一种类型强制转换为另一种类型,这就是代码失败的原因。
你有几个选择。这里有一个:
let action = self.info?["action"] // An optional
if let action = action as? String {
// You have your String, process as needed
} else if let action = action as? NSNull {
// It was "null", process as needed
} else {
// It is something else, possible nil, process as needed
}发布于 2017-06-28 23:53:46
试试这个。因此,在第一行中,首先检查是否存在有效的"action“值,然后检查该值是否为String类型
if let action = self.info?["action"] as? String {
switch action{
....
}
} else {...}发布于 2017-06-29 00:03:30
if let action = self.info?["action"] { // Unwrap optional
if action is String { //Check String
switch action {
....
}
} else if action is NSNull { // Check Null
print("action is NSNull")
} else {
print("Action is neither a string nor NSNUll")
}
} else {
print("Action is nil")
}https://stackoverflow.com/questions/44807261
复制相似问题