Can the conversion of a String to Data with UTF-8 encoding ever fail?
In order to convert a
String instance to a
Data instance in Swift you can use
data(using:allowLossyConversion:), which returns an optional
Can the return value of this function ever be
nil if the encoding is UTF-8 (
If the return value cannot be
nil it would be safe to always force-unwrap such a conversion.
- NSString with emoticons/emojis url encode
- Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?
- Converting NSString to Base64 Data for XML Serialization
- String(data: data, encoding: NSUTF8StringEncoding) return nil
- Does not conform to protocol 'NSCoding' - Swift 3
- URL encoding iOS NSURL error
Solutions Collect From Internet About “Can the conversion of a String to Data with UTF-8 encoding ever fail?”
UTF-8 can represent all valid Unicode code points, therefore a conversion
of a Swift string to UTF-8 data cannot fail.
The forced unwrap in
let string = "some string .." let data = string.data(using: .utf8)!
The same would be true for
.utf32, but not for
encodings which represent only a restricted character set,
You can alternatively use the
.utf8 view of a string to create UTF-8 data,
avoiding the forced unwrap:
let string = "some string .." let data = Data(string.utf8)
- Avoid consecutive “if let” declarations in Swift
- Error-63(file name too long) while unzipping a zip file downloaded from GitHub
- How to distribute Java application 7.0 and above on Mac 10 and above?
- IOS UIMenuController UIMenuItem, how to determine item selected with generic selector method
- Comparison between TestFlight Live, QuincyKit and Crashlytics
- How to save and retrieve NSObject class using NSUserDafaults in iOS
- Swift Language Multicast Delegate
- Retrying an asynchronous operation using ReactiveCocoa
- How do I create blurred text in an iPhone view?
- webview having trouble with redirects
- How to detect if the device is an iPhone 5?
- Correcting floating point numbers
- swift animation does not go through all keyframes
- Dismiss UITableViewRowAction
- How to Fix Error with a Swift NSTimer Calling Its Selector