Last active
February 26, 2022 02:43
-
-
Save mironal/8aa26f3c10b8b2f878dea297033b53b2 to your computer and use it in GitHub Desktop.
Split Data by other Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let datas = "abc\r\n\r\n123\r\nγγγπ\r\nAB\r\n".data(using: .utf8)! | |
let delim = "\r\n".data(using: .utf8)! | |
extension Data { | |
func split(separator: Data, omittingEmptySubsequences: Bool = true) -> [Data] { | |
var current = startIndex | |
var chunks = [Data]() | |
while let range = self[current...].range(of: separator) { | |
if !omittingEmptySubsequences { | |
chunks.append(self[current..<range.lowerBound]) | |
} else if range.lowerBound > current { | |
chunks.append(self[current..<range.lowerBound]) | |
} | |
current = range.upperBound | |
} | |
if current < self.endIndex { | |
chunks.append(self[current...]) | |
} | |
return chunks | |
} | |
} | |
let chunks = datas.split(separator: delim) | |
print("Count", chunks.count) | |
chunks.forEach { | |
print(String(data: $0, encoding: .utf8)!) | |
} | |
/* | |
Count 4 | |
abc | |
123 | |
γγγπ | |
AB | |
*/ | |
let chunks2 = datas.split(separator: delim, omittingEmptySubsequences: false) | |
print("Count", chunks2.count) | |
chunks2.forEach { | |
print(String(data: $0, encoding: .utf8)!) | |
} | |
/* | |
Count 5 | |
abc | |
123 | |
γγγπ | |
AB | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment