Search code examples
iosswift2xcode7ios9

Swift 2 + SwiftyJSON: Use of unresolved identifier error


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!


Solution

  • 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.