On Jun 16, 2015, at 11:54 AM, chris...@gmail.com wrote:I have a sequence of bytes in an array that might be a valid UTF-8 sequence. I can of course dip down into Foundation to convert these into a String, however I'm looking for a way to do this in "pure" Swift.
func decode<UnicodeCodec: UnicodeCodecType>(codeUnits: [UnicodeCodec.CodeUnit], var decoder: UnicodeCodec) -> String? {
var string = ""
var codeUnitGenerator = codeUnits.generate()
while true {
switch decoder.decode(&codeUnitGenerator) {
case .Result (let scalar):
string.append(scalar)
case .EmptyInput:
return string
case .Error:
return nil
}
}
}
--
You received this message because you are subscribed to the Google Groups "Swift Language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to swift-languag...@googlegroups.com.
To post to this group, send email to swift-l...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/swift-language/595462CD-AC45-4900-9F86-A05585D03A74%40mooseyard.com.
For more options, visit https://groups.google.com/d/optout.
There's a struct called UTF8 that encodes and decodes UTF-8 sequences into UnicodeScalars. Using it is a little cumbersome, but very doable:func decode<UnicodeCodec: UnicodeCodecType>(codeUnits: [UnicodeCodec.CodeUnit], var decoder: UnicodeCodec) -> String? {
var string = ""
var codeUnitGenerator = codeUnits.generate()
while true {
switch decoder.decode(&codeUnitGenerator) {
case .Result (let scalar):
string.append(scalar)
case .EmptyInput:
return string
case .Error:
return nil
}
}
}
On Jun 16, 2015, at 8:58 PM, Brent Royal-Gordon <br...@brentdax.com> wrote:There's a struct called UTF8 that encodes and decodes UTF-8 sequences into UnicodeScalars. Using it is a little cumbersome, but very doable:
--You received this message because you are subscribed to the Google Groups "Swift Language" group.To unsubscribe from this group and stop receiving emails from it, send an email to swift-languag...@googlegroups.com.To post to this group, send email to swift-l...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/swift-language/65fa3439-0d73-44a2-b645-70bc36f59c90%40googlegroups.com.