As @dan notes in the comments, this method is part of the tutorial you are looking at. Its ease in Swift without defining a custom method.
First, do not use NSMutableData
; instead, use a new Data
structure that will be either mutable or immutable depending on whether you use var
or let
:
var body = Data()
Then add the bytes of UTF-8:
body.append(Data("foo".utf8))
(There are other String
methods for other encodings if you need something other than UTF-8.)
If you need the exact behavior of a tutorial, then how to translate its method in Swift 3:
extension Data { mutating func append(string: String) { let data = string.data( using: String.Encoding.utf8, allowLossyConversion: true) append(data!) } } … body.append("foo")
I would not recommend this code for two reasons. First, lossy conversion means your application can silently discard important data. Secondly, a power reversal ( data!
Instead of Data
) means that in case of an encoding error, your application will crash, and not display a useful error.
source share