2016-10-06 62 views
0
if let service = dict["service"] as? [String: AnyObject] {//dict is JSON object 
     if let boolValue = service["isDeliverable"] {//Value is: false 
      let isTrueVal = boolValue as! Bool // Crash as Bool is not a type of AnyObject 
      let isTrueVal = boolValue as? Bool // Always returns nil 
     } 
    } 

如何投射Swift類型Bool的AnyObject?JSON AnyObject要布爾總是返回零

+0

使用調試器。 「boolValue」顯示什麼類型? – rmaddy

+0

@rmaddy:我已經提到過了。它是AnyObject ...我嘗試了所有轉換爲bool的方式...如果該值是數字可以轉換爲NSNumber N然後bool ...但是這裏的值是真/假 –

+0

您可以使用'NSNumber ''Bool'也是如此。 – OOPer

回答

1

As I found that using CFBoolean可以實現這一點:

CFBoolean對象用來包裝布爾值在覈心 基金財產清單和集合類型使用。

if let service = dict["service"] as? [String: AnyObject] { 
     if let boolValue = service["isDeliverable"] { 
      let isTrueVal = (boolValue as! CFBoolean) as Bool 
     } 
    }