2

I have a variable that has a string thats has an array in it. How do I convert it to just an array again in swift?

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

Convert to:

var featCatName2 = [home, pages, books, stores, groups, trips]
1
  • Why do you store the array as a string like this? What if one of the strings contains a comma? Commented Dec 17, 2014 at 20:24

2 Answers 2

4

The short answer is this one-liner:

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

This is also safe to call even when the array is empty :)

  1. var featCatName2 = "[home, pages, books, stores, groups, trips]"
    Declare your string "array"
  2. featCatName2 = featCatName2.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
    Trim away [] in both ends.
  3. let result = featCatName2.componentsSeparatedByString(", ")
    Explode the string into an array of strings.
Sign up to request clarification or add additional context in comments.

1 Comment

I was just going to suggest this. I'd probably make it a two-liner, though.
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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.