我有一个变量,它有一个字符串,其中有一个数组。如何在swift中将其再次转换为数组?

var featCatName2 = "[home, pages, books, stores, groups, trips]"

转换为:
var featCatName2 = [home, pages, books, stores, groups, trips]

最佳答案

简短的答案是这一行:

var featCatName2 = "[home, pages, books, stores, groups, trips]"
let result = featCatName2.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")

即使数组为空,也可以安全地调用:)
var featCatName2 = "[home, pages, books, stores, groups, trips]"
声明字符串“array”
featCatName2 = featCatName2.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
修剪两端的[]。
let result = featCatName2.componentsSeparatedByString(", ")
将字符串分解为字符串数组。

09-12 16:05