2

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]

4
  • 1
    Why are you storing an array as a string like this? Commented Jul 9, 2017 at 2:11
  • Because I don't know what else to do. Im using firebase and this way I'll be able to store multiple points of data in only one node. Do you think there is a better way of going about this? Commented Jul 9, 2017 at 2:14
  • 1
    If you insist on storing an array of values as a string, at least create a string that is much easier to split back into an array. Get rid of the spaces after each comma and get rid of the square brackets. It would probably help if you updated your question with code showing how you create the string from an array. And you need to worry about strings in the array that contain commas to begin with. Commented Jul 9, 2017 at 2:16
  • 1
    firebase.googleblog.com/2014/04/… Commented Jul 9, 2017 at 3:58

2 Answers 2

2

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{

}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.