slysid
slysid

Reputation: 5498

Updating value - SwiftyJSON

I have a json object as below

{"level" :{"currentLevel":"1","score":"100"}}

I have this json data in my project folder and I am using SwiftyJSON to parse my son and read the values. Everything looks fine.

Now I need to update the score and I am trying as below

var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
json["level"]["score"] = "200"

This works fine too and the json is updated but below try fails

var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
var updatedScore:String = "200"
json["level"]["score"] = updatedScore

I get compile error

Type [Subscript] does not conform to Protocol 'StringLiteralConvertible'

Any suggestion on how to update a SwiftJSON JSON object with a variable would be helpful

Thank you

Update:My Solution

This is what I have done finally

    var json = JSON({"level" :{"currentLevel":"1","score":"100"}})
    var level = (json["level"] as JSON).dictionaryObject
    let updatedScore = "200"
    level!["currentLevel"] = updatedScore
    json["level"] = JSON(level!)

And this works

Upvotes: 0

Views: 1740

Answers (1)

chirag90
chirag90

Reputation: 2240

Try the below if you are saving the json as dictionary

((json["level"]as nsdictionary)["score"] as NSString = updatedScore)

Upvotes: 2

Related Questions