将字符串转换回数组

时间:2014-12-17 20:11:25

标签: arrays variables swift

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

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

转换为:

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

2 个答案:

答案 0 :(得分:4)

简短的回答是这个单行:

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

即使数组为空,这也可以安全地调用:)

  1. var featCatName2 = "[home, pages, books, stores, groups, trips]"
    声明你的字符串“array”
  2. featCatName2 = featCatName2.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
    两端修剪[]。
  3. 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"]