Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64EncodedStringWithOptions in Swift fails with compile error

Tags:

ios

swift

base64

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.

like image 770
Mikhail Larionov Avatar asked Jul 15 '14 22:07

Mikhail Larionov


3 Answers

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: [])
like image 113
slazyk Avatar answered Sep 20 '22 16:09

slazyk


For Swift 2.x use an array for options:

let dataStr = data.base64EncodedStringWithOptions([.Encoding64CharacterLineLength])
let dataStr = data.base64EncodedStringWithOptions([])
like image 24
zaph Avatar answered Sep 21 '22 16:09

zaph


For swift 3.0+ use this ,

var dataStr = data.base64EncodedString(options: .lineLength64Characters)
like image 32
Kiran P Nair Avatar answered Sep 22 '22 16:09

Kiran P Nair