簡體   English   中英

如何從嵌套數組返回值-Swift 3

[英]how to return value from nested array - swift 3

我的api查詢正在數組中返回多個值(如下所示),我需要將其用於其他功能。 如何獲取嵌套的值60?

我的代碼例如, let uid = value["uid"] as? String let uid = value["uid"] as? String可以很好地返回uid和name。 但是, let rest = value["field_resting_bpm"] as? String let rest = value["field_resting_bpm"] as? String返回nil。

如何更正此行以返回嵌套值“ 60” ?:

 let rest = value["field_resting_bpm"] as? String'

api查詢為:

    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

var checkUserEndpoint:字符串=“ https://example.site/ios1/user/1.json

   Alamofire.request(.GET, checkUserEndpoint, parameters: nil, headers: headers, encoding: .JSON)
        .responseJSON { response in
            guard response.result.error == nil else {
                print("ran alamofire")
                //got an error in getting the data, need to handle it
                print("error calling GET")
                print(response.result.error!)
                return
            }

            guard let value = response.result.value else {
                print("no result data received when calling GET")
                return
            }
            // return UID
            print("ran alamofire")
            var datareturned = JSON(value)
            print("VALUE: \(value)")

它在我的控制台中返回:

 uid = 1;
 name = "Guest User";
"field_resting_bpm" =     {
    und =         (
                    {
            value = 60;
        }
    );

更新:此字段是Drupal用戶帳戶設置中的整數。 我添加了一個名為field_rest_bpm_string的文本字段(因此它應該返回一個字符串),也用於測試

網站上的json返回:

“ field_resting_bpm”:{“ und”:[{“ value”:“ 60”}]},“ field_rest_bpm_string”:{“ und”:[{“ value”:“ 65”,“ format”:null,“ safe_value” :“ 65”}]}

注意 :代碼在Swift 3中,但是您可以輕松地在swift 2中進行轉換SwiftyJSON版本代碼在2和3中相同。

如果您使用的是SwiftyJSON那么事情就簡單得多

let value = datareturned["field_resting_bpm"]["und"][0]["value"].stringValue
print(value)

如果您不使用SwiftyJSON

let rest = value["field_resting_bpm"] as? NSDictionary
let und = (rest?.value(forKey: "und") as! NSArray).object(at: 0) as! NSDictionary
let yourValue = und.value(forKey: "value") as! String

這樣的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM