2016-05-14 31 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