Last active
July 11, 2016 16:00
-
-
Save amake/ec967e032493f32e7498 to your computer and use it in GitHub Desktop.
Naked Unicode surrogates in Swift
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
| // Making strings of "normal" Unicode is pretty easy: | |
| // Unicode Scalar literal | |
| "\u{2603}" // "☃" | |
| // From int | |
| String(UnicodeScalar(0x2603)) // "☃" | |
| // Maybe you want to test how your app handles weird Unicode input, like naked surrogates. | |
| // But Swift makes it pretty hard to create such strings. | |
| "\u{d800}" // Invalid unicode scalar | |
| UnicodeScalar(0xd800) // EXC_BAD_INSTRUCTION | |
| var gen = GeneratorOfOne(0xd800 as UInt16) | |
| var utf16 = UTF16() | |
| let result = utf16.decode(&gen) // Error | |
| // It turns out you can do it with NSString! | |
| let cc: [unichar] = [0xd800] | |
| NSString(characters: cc, length: cc.count) // "�" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment