Q: Swift: Split comma-separated strings, but not if comma enclosed in single quotes My XML file encodes strings in between single-quotes. Array elements are comma-separated.

'Hello', 'World'

Normally, extracting comma-separated values is easy:
let result = myString.split{ $0 == "," }.map(String.init)

The problem is that I can't recklessly split on the comma: if the comma is enclosed in single quotes it is text, otherwise it is an array element separator:

'Hello', 'World', 'Hello, World'

Should produce:
["Hello", "World", "Hello, World"]

Note two things:


*

*An empty single quotes is an empty string that can't be discarded (it's an element in an array)

*I can't guarantee whitespace between the elements; a user may have tampered with a file.



'Hello', 'World'     , 'Hello, World', ''

should produce: 
["Hello", "World", "Hello, World", ""]

I need some way to differentiate between a comma-separated value which lies outside of the single quotes: ', ' A better approach would probably be to retain anything in between single-quotes, but I don't know how to do this.

A: What about separating the string by single quotes and removing elements containing a single comma and a space afterwards?
Note that you should remove the first/last element of the result, since the input starts and ends with a single quote and that produces an empty element after separating.
var result = myString.components(separatedBy: "'").filter { 
    $0.trimmingCharacters(in: .whitespaces) != ","
}

result.removeLast()
result.removeFirst()

