Mikhail Larionov Mikhail Larionov - 1 month ago 41
iOS Question

base64EncodedStringWithOptions in Swift fails with compile error

let dataStr = data.base64EncodedStringWithOptions(options: Encoding64CharacterLineLength)


Doesn't compile with "Use of unresolved identifier 'Encoding64CharacterLineLength'"
When I just change the param to zero with

let dataStr = data.base64EncodedStringWithOptions(options: 0)


It gives even stranger error: "Cannot convert the expression of type 'String!' to type 'String!'" I found a way to init NSString with NSData (however, I still can't get the difference between String and NSString), but I'm really curious why these two lines of code don't work.

Answer

Unless explicitly given an external name, first argument of a method in Swift is not a named argument. Therefore you should be doing: data.base64EncodedStringWithOptions(x) without the options: part.

If you actually look at the argument type, NSDataBase64EncodingOptions, you'll notice that it is a struct conforming to RawOptionSet with static variables for option constants. Therefore to use them you should do: NSDataBase64EncodingOptions.Encoding64CharacterLineLength

The NSDataBase64EncodingOptions struct (or RawOptionSet in general) is also not convertible from integer literals (like 0). But it does conform to NilLiteralConvertible so if you don't want any options you can pass nil.

Putting it together:

let dataStr = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

or

let dataStr = data.base64EncodedStringWithOptions(nil)

Swift3.0

let dataStr = data.base64EncodedString(options: [])