说我有一个变量
function configureChannel( obj, Channel )
myStruct.Channel = Channel;
save -append registers.mat myStruct;
end
function updateConfiguration( obj, dataPath )
myStruct.EN = 1;
save -append registers.mat myStruct;
end
现在让我们有一个数组<串GT;
let stringArray = "[\"You\", \"Shall\", \"Not\", \"PASS!\"]"
// if I show this, it would look like this
print(stringArray)
["You", "Shall", "Not", "PASS!"]
现在说我该怎么做才能转换变量' stringArray'到'数组<串GT;'
答案 0 :(得分:1)
答案是使用NSJSONSerialization转换字符串
感谢Vadian提示
let dataString = stringArray.dataUsingEncoding(NSUTF8StringEncoding)
let newArray = try! NSJSONSerialization.JSONObjectWithData(dataString!, options: []) as! Array<String>
for string in newArray {
print(string)
}
瞧,你有它,它现在是一个字符串数组
答案 1 :(得分:0)
Swift 4的小改进。
试试这个:
// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)
分别对于其他数据类型:
// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)