使用 guard 语句从 json 解包到 AnyObject
Unwrap with guard statement from json to AnyObject
我需要从 json 文件中的字典(包含相同的键)中解析数据。问题是在某些字典中,同一个键的值是一个字符串,但在另一个字典中它是一个浮点数。 (可选阅读:原因是我使用的 csv 到 json 转换器确实将负十进制数识别为字符串,因为破折号后有一个空白 space:“- 4.50”。我会删除 space 并在字符串展开后转换为浮动。)
我尝试了以下操作:
guard let profit = data["profit"] as? AnyObject else { return }
if profit as! Float != nil {
// Use this value
} else {
// It is a string, so delete the space and cast to float
}
必须有一个简单的解决方法,但无论我如何放置?和 !在 guard 语句中,编译器会报错。
无论如何,字典值的默认类型是AnyObject
,所以这种类型转换是多余的。
您可以使用 is
操作数
简单地检查类型
guard let profit = data["profit"] else { return }
if profit is Float {
// Use this value
} else {
// It is a string, so delete the space and cast to float
}
或包括适当的类型转换
guard let profit = data["profit"] else { return }
if let profitFloat = profit as? Float {
// Use this value
} else if let profitString = profit as? String {
// It is a string, so delete the space and cast to float
}
我需要从 json 文件中的字典(包含相同的键)中解析数据。问题是在某些字典中,同一个键的值是一个字符串,但在另一个字典中它是一个浮点数。 (可选阅读:原因是我使用的 csv 到 json 转换器确实将负十进制数识别为字符串,因为破折号后有一个空白 space:“- 4.50”。我会删除 space 并在字符串展开后转换为浮动。)
我尝试了以下操作:
guard let profit = data["profit"] as? AnyObject else { return }
if profit as! Float != nil {
// Use this value
} else {
// It is a string, so delete the space and cast to float
}
必须有一个简单的解决方法,但无论我如何放置?和 !在 guard 语句中,编译器会报错。
无论如何,字典值的默认类型是AnyObject
,所以这种类型转换是多余的。
您可以使用 is
操作数
guard let profit = data["profit"] else { return }
if profit is Float {
// Use this value
} else {
// It is a string, so delete the space and cast to float
}
或包括适当的类型转换
guard let profit = data["profit"] else { return }
if let profitFloat = profit as? Float {
// Use this value
} else if let profitString = profit as? String {
// It is a string, so delete the space and cast to float
}