Search code examples
swiftbase64alamofirebasic-authentication

Printing a string results in (Function) in console. Why?


I'm trying to create a base64 basic authentication header for use with an API. In swift 2.0 and iOS9 it's started to give me problems, so I'd like to examine the contents of headers or base64Credentials. Unfortunately, all I see is (Function).

    let credentialData = "[email protected]:demo123".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions  

    let headers = ["Authorization": "Basic \(base64Credentials)"]

    print("Here are the base64 encoded headers \(base64Credentials)")

Yields

Here are the base64 encoded headers (Function)

How can I figure out what the values of these strings are?

Am I missing something new in Swift 2.0 that has suddenly made this a problem?

Thank you,

Josh


Solution

  • public func base64EncodedStringWithOptions(options: NSDataBase64EncodingOptions) -> String
    

    is an instance method. Functions and methods are called with zero or more arguments in parentheses. In this case we have one argument, which can be [] for no options:

    let credentialData = "[email protected]:demo123".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])  
    
    print("Here are the base64 encoded headers \(base64Credentials)")
    // Here are the base64 encoded headers ZGVtb0BkZW1vLmNvbTpkZW1vMTIz
    

    In your code

    let base64Credentials = credentialData.base64EncodedStringWithOptions
    

    the method itself is assigned to the variable, and that prints as "(Function)".

    Am I missing something new in Swift 2.0 that has suddenly made this a problem?

    No, this would be the same issue in Swift 1.2. The only difference is the type of the parameter, in Swift 1.2 you would specify "no options" as nil instead of [].