Search code examples
swiftswift2named-parameters

Swift: Why no labeled arguments in this situation?


For this code

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString

I will have forgot what the third argument stands for, soon.

For some reason Swift (2.0) doesn't allow me to label the arguments like that:

let documentsPath = NSSearchPathForDirectoriesInDomains(directory: .DocumentDirectory,
domainMask: .UserDomainMask, expandTilde: true)[0] as! NSString  // error

I really hope I'm missing something!
Or rather: I really hope I don't have to miss the single best feature from Objective-C.


Solution

  • It has to do with the way the function is defined. If it isn't defined with named arguments, you can't call it with named arguments.

    NSSearchPathForDirectoriesInDomains is either a C style function (not a method) or a compiler macro that generates inline code. (It looks to me like it's a C function.) Neither of those accept named arguments, so you can't.

    If you really want to stay away from unnamed arguments, create a utilities class that provides glue code that accepts named arguments and then calls the function in question. That way you encapsulate the old-style code in only one place. There will be a (tiny) performance cost to the extra function call, but in nearly all cases it will be unnoticeable.