SwiftyJSON JSON Object as a Class Property

I am working with SwiftyJSON which is great. I am however having an issue with storing the JSON(data:) result in a property in my viewController. The standard use of SwiftyJSON works fine.


let json = JSON(data: data) let name = json[1]["name"].string


My problem occurs when I try to create a property to store the result of JSON(data:)


     var jsonData : JSON?


     someMethod()
     { 
          let json = JSON(data: data) 
          self.jsonData = json 
          if let name = self.jsonData[1]["name"].string 
          { 
               print(name) 
          } 
     }


When I do this I get an error on the following line.


if let name = self.jsonData[1]["name"].string

Cannot find member 'string'


Does anyone know why this is?

Answered by QuinceyMorris in 14548022

Using a fake JSON class definition, the following works in a playground:


if let name = self.jsonData?[1]["name"].string


I think the issue is that the 'let' "understands" the optionality in your jsonData property, but the chained operators inside the expression don't.

Accepted Answer

Using a fake JSON class definition, the following works in a playground:


if let name = self.jsonData?[1]["name"].string


I think the issue is that the 'let' "understands" the optionality in your jsonData property, but the chained operators inside the expression don't.

Brilliant. Thank you.

Take care,


Jon

Try:

var json: JSON = JSON.nullJSON


someMethod() 
     {  
          let json = JSON(data: data)  
          self.jsonData = json  
          if let name = self.jsonData[1]["name"].string  
          {  
               print(name)  
          }  
     }
SwiftyJSON JSON Object as a Class Property
 
 
Q