SwiftyJSON Property Trouble

72 views Asked by At

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:)

// Property    
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?

1

There are 1 answers

0
amit Sharma On BEST ANSWER

You are using an optional property.

var jsonData : JSON?

just use

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

in place of

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

in your case complier trying to find a property which can be a nil.