2

I'm making an API REST application in Swift 2 with iOS 9, using SwiftyJSON support for Swift 2 (https://github.com/andrelind/SwiftyJSON). When I get my data and print it, I use this code:

RestApiManager.sharedInstance.getRandomUser { json in
  let results = json["results"]
  for (index: String, subJson: JSON) in results{
      var user = subJson["user"].string
      print(user)
  }
}

With this code, I'm getting this error:

var user = subJson["user"].string

Use of unresolved identifier 'subJson error'

And According with Swift 2 documentation, a loop with dictionary is like:

for (key, value) in source{
  //Do something
}

And SwiftyJSON documentation I can use it in this way:

for (key: String, subJson: JSON) in json {
    //Do something you want
}

Anyone know why I receiving this error if in theory the declaration is correct. I'm using Xcode 7.0 beta 3, Swift 2 and my project if for iOS 9. Thanks!

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • According with SwiftyJSON documentation: //Getting a string using a path to the element let path = [1,"list",2,"name"] let name = json[path].string – Javier Landa-Torres Aug 02 '15 at 17:51

2 Answers2

4

You are confusing the internal name of the parameter and the actual parameter that the iteration gives you. The following should work:

// demo JSON
let json = ["results" : ["first" : ["user" : 123], "second" : ["user" : 456], "third" : ["user" : 789]]]

let results = json["results"]!
for (index: String, subJson: JSON) in results {
    var user = JSON["user"]
    print(user)
}

To make it a little bit more clear:

for (index: myIndex, subJson: mySubJSON) in results {
    var user = mySubJSON["user"]
    print(user)
}

The subJSON is not the name of the variable containing your json, the name is JSON / mySubJSON, same goes for the index.

luk2302
  • 55,258
  • 23
  • 97
  • 137
0

Try with this:

RestApiManager.sharedInstance.getRandomUser { (json) -> Void in
            let results = json["result"]
            for result in results {
                let user = result.1["user"].object
                print(user)
            }
        }

Your results will return a (key, value), so when you code result.1["user"], you will receive the value of result

Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116