2016-05-14 71 views
1

我需要从json文件中的字典(包含相同的键)解析数据。问题在于,在一些字典中,同一个键的值是一个字符串,但是在另一个字符串中是浮点数。 (可选地阅读:原因是我使用的csv to json转换器确实将一个负数的十进制数识别为一个字符串,因为短划线之后有一个空格:“ - 4.50”。我将删除该空格并将其强制转换为一次浮动该字符串被解开)从json向AnyObject展开警戒声明

我试着做到以下几点:。

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 
} 

必须有这样的一个简单的办法,但无论我怎么把?和!在守卫声明中,编译器会抱怨。

回答

1

无论如何,字典值的缺省类型是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 
} 
+0

非常感谢,认为没有的伎俩! – nontomatic