swift - Retrieving values from 2D array in JSON string -
we fetch json data using rest protocol this.
jsonresult = try nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions.allowfragments)
which looks this:
jsonresult: ( { board = "[[\"1:\",\"y\",\"u\",\"p\"]]"; })
from game board so:
if let boardcontentarray = jsonresult[0]["board"] nsarray?{ print("boardcontentarray: \(boardcontentarray)" ) } else { print("board element not nsarray") }
the boardcontentarray looks this: supposed 2d array 1 row , 4 columns @ moment, should should work given size.
[["1:","y","u","p"]]
how can retrieve individual values of boardfromremote. imagine element @ 0,0 in 2d array way this:
boardcontentarray[0][0]
this should return "1:", not case. exact syntax incorrect , won't compile. correct way retrieve element boardcontentarray variable?
the content of jsonresult[0]["board"]
json string can decoded array nsjsonserialization. have first transform string nsdata, decode example:
do { let boardcontentarray = "[[\"1:\",\"y\",\"u\",\"p\"]]" // string jsonresult[0]["board"] if let boarddata = boardcontentarray.datausingencoding(nsutf8stringencoding), let boardarray = try nsjsonserialization.jsonobjectwithdata(boarddata, options: []) as? [[string]] { print(boardarray[0]) // ["1:", "y", "u", "p"] } } catch let error nserror { print(error) }
Comments
Post a Comment