转换阵列为字符串,然后回到阵
说我有一个变量转换阵列<String>为字符串,然后回到阵<String>
let stringArray = "[\"You\", \"Shall\", \"Not\", \"PASS!\"]"
// if I show this, it would look like this
print(stringArray)
["You", "Shall", "Not", "PASS!"]
现在让我们有一个数组<字符串>
let array = ["You", "Shall", "Not", "PASS!"]
// if I convert this into string
// it would roughly be equal to the variable 'stringArray'
if String(array) == stringArray {
print("true")
} else {
print("false")
}
// output would be
true
现在说我应该怎么做才能转换变量“ stringArray'to'Array < String>'
答案将是使用NSJSONSerialization转换字符串
感谢Vadian为尖
let dataString = stringArray.dataUsingEncoding(NSUTF8StringEncoding)
let newArray = try! NSJSONSerialization.JSONObjectWithData(dataString!, options: []) as! Array<String>
for string in newArray {
print(string)
}
瞧你有它,它现在是一个字符串数组
然后你应该接受你的答案:) –
'mutableContainers'在Swift中完全没用,只是读取它不需要的数据。 – vadian
@AhmadF我应该等待2天才能接受我自己的回答 –
[这个问题](http://stackoverflow.com/questions/24111764/does- swift-provide-the-ability-to-eval-swift-code-like-javascript-does)表明在Swift中没有'eval'操作,所以你可以写一个小解析器。 – Gabriel
这是JSON。使用'(NS)JSONSerialization'类。 – vadian
所以我不得不把它从地狱中解脱出来?这是我现在正在考虑这样做的唯一方法..悲伤地 –