Swift Convert A String-As-An-Array, To An Array Of Strings -
i have string:
"["word1","word2"]"
and want simple way convert actual [string]
.
all other questions dig on there converting int strings arrays.
i tried doing
array(arrayliteral: "["word1","word2"]")
but get
["[\"word1\",\"word2\"]"]
manually cleaning edges , removing slashes seems i'm doing wrong.
i'm curious if there's simple way convert array of strings string array of strings.
i.e. convert "["word1","word2"]"
["word1","word2"]
solution (thanks @eric d)
let data = stringarraystring.datausingencoding(nsutf8stringencoding) var stringsarray:[string]! { stringsarray = try nsjsonserialization.jsonobjectwithdata(data!, options: []) as? [string] } catch { print() } print("array \(stringsarray)")
encode "string array" data, decode data json swift array.
like this, example:
let source = "[\"word1\",\"word2\"]" guard let data = source.datausingencoding(nsutf8stringencoding), arrayofstrings = try nsjsonserialization.jsonobjectwithdata(data, options: []) as? [string] else { fatalerror() } print(arrayofstrings) // ["word1", "word2"] print(arrayofstrings[1]) // "word2"
Comments
Post a Comment