使用SwiftyJson在swift中,True变为false

时间:2017-07-27 09:16:16

标签: swift swifty-json

使用.boolValue时,我得到一个布尔值的相反值 我有这个代码。

let _ = channel.bind(eventName: "like-unlike-cake", callback:  
  {(data:Any?)->Void in
let likedCake = JSON(data!)["like"]
print("liked cake: \(likedCake)")
print("Boolean: \(likedCake["liked_by_current_user"].boolValue)")

liked cake: {
    "liked_by_current_user" : true
}
}
Boolean: false

但是当我使用.bool时,它给了我零。有人帮我这个。

UPDATE这将是我想要获取的json

{
 "like": {
 "id": "66642122-7737-4eac-94d2-09c9a35cbef8",
 "liked_by_current_user": true
 }
}

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

let _ = channel.bind(eventName: "like-unlike-cake", callback {
   (data:Any?)->Void in

    if let jsonData = data {
         let json = JSON(jsonData)
         let isLikedByCurrentUser = json["like"]["liked_by_current_user"].boolValue
         print(isLikedByCurrentUser)
    } else {
         // your data is nil
         debugPrint("data error")
    }
}

您也可以尝试将data: Any转换为Data,方法是替换该行:

if let jsonData = data as? Data {
     let json = JSON(data: jsonData)...

因为有时SwiftyJSON在从Any创建JSON对象时遇到问题。

相关问题