- Split string by
|
character
- Then append elements that not a number in last subarray of resulted array
- If element is number, then add new subarray to resulted array
- Repeat 2-3 until you done
let input = "001|apple|red|002|banana|yellow|003|grapes|purple"
let result: [[String]] = input
.split(separator: "|")
.reduce(into: []) { result, string in
guard let _ = Int(string) else {
result[result.count - 1].append(String(string))
return
}
result.append([])
}
/// result: [["apple", "red"], ["banana", "yellow"], ["grapes", "purple"]]
If you want persist 001
as well, then change result.append([])
to result.append([String(string)])
:
[["001", "apple", "red"], ["002", "banana", "yellow"], ["003", "grapes", "purple"]]
Important
This solution expect that your string will start with number or crash otherwise.
If you can't guaranteed that your string starts with number, that you need to manually check that array not empty in guard block.