Referencing functions with default parameters

Hello,

In Swift you can reference a function with it's complete name. For example, if you have the following functions:

func add(num1: Int, num2: Int) -> Int
func add(num1: Int, num2: Int, num3: Int) -> Int

Then you can get a reference to the second like this:

let function = add(num1:num2:num3:)

Works well.

Imagine now, that you have some similar functions with default parameters to log to a file as a debug-log, warning or error, for example:

func debug(_ message: String, eventid: String = Foundation.UUID().uuidString, logFile: String = "log.log", evenIdents: Bool = true) -> String

func warning(_ message: String, eventid: String = Foundation.UUID().uuidString, logFile: String = "log.log", evenIdents: Bool = true) -> String

func error(_ message: String, eventid: String = Foundation.UUID().uuidString, logFile: String = "log.log", evenIdents: Bool = true) -> String

If you want to reference the functions, for example, in a switch, it's not possible like this (omitting two default parameters):

let function: (String, String) -> String    

switch logStyle {
case .debug:
    function = Log.debug(_:logFile:) // Error
case .warning:
    function = Log.warning(_:logFile:) // Error
case .error:
    function = Log.error(_:logFile:) // Error
}

Although you can call one of them like this:

Log.debug("Hello World!", logFile: "log.log")

I think, this should be possible, and also that it improves the consistency of Swift.

What do you think about it?

Best regards
Josef Zoller

3 Likes

I ran into this exact same issue yesterday. I think this solution makes sense.

Terms of Service

Privacy Policy

Cookie Policy