我有一个变量,其中包含一个包含数组的字符串。如何在swift中再次将其转换为数组?
var featCatName2 = "[home, pages, books, stores, groups, trips]"
转换为:
var featCatName2 = [home, pages, books, stores, groups, trips]
答案 0 :(得分:4)
简短的回答是这个单行:
var featCatName2 = "[home, pages, books, stores, groups, trips]"
let result = featCatName2.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")
即使数组为空,这也可以安全地调用:)
var featCatName2 = "[home, pages, books, stores, groups, trips]"
featCatName2 = featCatName2.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
let result = featCatName2.componentsSeparatedByString(", ")
答案 1 :(得分:1)
public extension String {
var count: Int {
return countElements(self)
}
subscript (i: Int) -> String {
return String(Array(self)[i])
}
subscript (r: Range<Int>) -> String {
var start = advance(startIndex, r.startIndex)
var end = advance(startIndex, r.endIndex)
return substringWithRange(Range(start: start, end: end))
}
}
var featCatName2 = "[home, pages, books, stores, groups, trips]"
let resultArray = featCatName2[1...featCatName2.count-2].componentsSeparatedByString(", ") // ["home", "pages", "books", "stores", "groups", "trips"]