Split by more than one separator
Using split
Swift 4
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split { [",", "[", "]"].contains($0.description) }
Swift 3
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split { [",", "[", "]"].contains($0.description) }
Swift 2
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split(isSeparator: {[",", "[", "]"].contains($0)}) }
Using characterSet
Swift 4
let str = "[0, 1, 2, 1]"
let separatorSet = CharacterSet(charactersIn: ",[]")
let comps = str.components(separatedBy: separatorSet)
Swift 3
let str = "[0, 1, 2, 1]"
let separatorSet = CharacterSet(charactersInString: ",[]")
let comps = str.components(separatedBy: separatorSet)
Swift 2
let str = "[0, 1, 2, 1]"
let separatorSet = NSCharacterSet(charactersInString: ",[]")
let comps = str.componentsSeparatedByCharactersInSet(separatorSet)
No matter what method we will use, and as a result, you will receive array. Without the information, which separator was used
If you need only convert String to Double then
let array = stringArray.compactMap { element -> Double? in
if let value = Double(element) {
return value
}
let parts = element.components(separatedBy: "/")
guard parts.count == 2,
let dividend = Double(parts[0]),
let divisor = Double(parts[1]),
divisor != 0
else {
return nil
}
return dividend / divisor
}