JSON AnyObject to Bool cast总是返回nil

时间:2016-10-06 22:00:09

标签: ios swift

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?

1 个答案:

答案 0 :(得分:1)

As I found that using CFBoolean可以做到这一点:

  

CFBoolean对象用于包装布尔值以供在Core中使用   基金会财产清单和收款类型。

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