Unless you know exactly where the data comes from, you shouldn't rely on decoding to succeed, and you shouldn't force-unwrap the string. utf8) // nilĪs we can see, decoding fails. We can try to remove the "e" from the array, so that the mark has no character left to modify: The last two bytes are the mark on top of the "é" and the "e". When you read some bytes, you never know if it's valid Unicode. Converting data into a string can always fail.įor example, here are the bytes for the cafe variable above: How about the other way around? When we want to convert data into a string, can we be sure it's safe to force-unwrap? In this case, the answer is an unqualified no. This isn't limited to emoji, Unicode can represent vastly more characters than ASCII. ascii)ĪSCII can't represent emoji, and the conversion will fail. When you use other encodings, it is not safe to force-unwrap (unless you explicitly know that a string is guaranteed to be representable). Strings in Swift use Unicode internally, so encoding a string using a Unicode encoding will always succeed. When you use a Unicode encoding (such as. Is it safe to force-unwrap this value? Can it ever return nil? It depends. When converting a string into data, the return type is optional.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |