I'm receiving a string from the server in the following format:
118|...message...215|...message2...
Basically, it's the message length followed by a pipe and the message itself, repeated for multiple messages. The message is encoded UTF16.
I'm looking for a way to parse this in Swift. I know I could cast this as NSString
and use standard indexes/ranges on that because UTF16 is what NSString uses, but I'm wondering what is the Swift way to handle this? I can't seem to find a way to pull a substring out of a String
based on a UTF16 encoding.
Update
I'm not trying to initialize a String
with raw UTF16 Data (there's plenty of ways to do that). I already have the string, so I'm trying to take a String
in the above format and parse it. The issue I have is that the message length given to me by the server is based on UTF16. I can't simply extract the length and call String.advance(messageLength)
on the Index because the length I've been given doesn't match the grapheme clusters that Swift advances on. My issue is that I can't extract from the string the message in Swift. I have to instead cast it over to NSString
and then use "normal" NSRange
on it. My question is how do I pull the substring out by extracting a range based on my search for the first pipe, and then use the length provided by the parser in UTF16.
This is all extremely simple to do with NSString
. Not sure how it can be done in pure Swift (or if it can be done).