If I got correct what you want to receive as a result, then this code would make what you want:
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, self.count)])
}
}
}
let src = "001|apple|red|002|banana|yellow|003|grapes|purple"
let result = src.split(separator: "|").map(String.init).chunked(into: 3)
// result = [["001", "apple", "red"], ["002", "banana", "yellow"], ["003", "grapes", "purple"]]
This will work if you know the expected size of resulting subarrays
You can also remove .map(String.init)
from the last line if it's ok for you that array elements are of type String.SubSequence