Big Johnson
Big Johnson

Reputation: 217

How to convert a string containing an array to an array swift

If I have a string that looks similar to this (stored in firebase):

"[brown, black, blue, pink]"

How would I convert this to in swift [brown, black, blue, pink]

Upvotes: 2

Views: 598

Answers (2)

Fangming
Fangming

Reputation: 25260

Parse it as a JSON array

let data = stringArray.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String]

    let first= json?[0] as? String
    dump(first)
}catch let error{

}

Upvotes: 2

Palle
Palle

Reputation: 12129

You can use the let components = yourString.components(separatedBy: ", ") function to separate the individual elements of your array. Then you can remove the first character (the "[") from your first string with components[0].remove(at: components[0].startIndex), and the last characters of the last element using components[components.count - 1].substring(to: components[components.count - 1].index(before: components[components.count - 1].endIndex)).

If you're using Swift 4 you can just use components[0].dropFirst() and components[components.count - 1].dropLast().

But as rmaddy stated, you should think about storing your data in a better way (using JSON or something similar), as someone could just enter "hello, world" which would be split into two components using this method.

Upvotes: 0

Related Questions