Mirwais Mirwais - 1 year ago 113
Swift Question

How to convert a JSON string into a normal string in Swift?

I use SwiftyJSON to get data in JSON format from an API. This data is stored into a variable which I want to convert into a String.

I have the following:

func parseJSON() {

let path2 = NSURL(string: "https://pokeapi.co/api/v2/pokemon/5")
let jsonData2 = NSData(contentsOfURL: path2!) as NSData!
let readableJSON2 = JSON(data: jsonData2, options: NSJSONReadingOptions.MutableContainers, error: nil)

numberOfRows = readableJSON2["name"].count //maybe hardcode this in the future?

let id = readableJSON2["id"]
let name = readableJSON2["name"]
let weight = readableJSON2["weight"]
let height = readableJSON2["height"]


Note that the idArray is a String array:

var idArray = [String]()

The NSLog("(id)") returns a 5. I want this 5 to be a string, but I don't know how. I tried the following:

var id = readableJSON2["id"].string as String!

but this results into a nil..

Any ideas?

Answer Source

You need to typecast the value rather than force unwrap it as a String, as so:

var id = String(readableJSON2["id"])

Let me know if that works.