Why does a function call require the parameter name in Swift?

后端 未结 6 1204
夕颜
夕颜 2020-11-27 10:42

I have this Function in a class:

func multiply(factor1:Int, factor2:Int) -> Int{
    return factor1 * factor2
}

I try to call the functi

相关标签:
6条回答
  • 2020-11-27 10:57

    since you used calculator.multiply() in the example code I'm assuming this function is a method of the calculator object.

    Swift inherits a lot of things from objective-c and this is one of them:

    When in objective-c you would do (hypothetically):

    [calculator multiply:@9834 factor2:@2321];
    

    the equivalent in Swift is:

    calculator.multiply(9834, factor2:2321);
    
    0 讨论(0)
  • 2020-11-27 10:59

    Because your "multiply" function is a method, and like Objective-c, the parameters in methods are part of the name.

    For example you can do this.

    class Calculator {
    
        func multiply(factor1:Int, factor2:Int) -> Int{
            return factor1 * factor2
        }
    
        func multiply(factor1:Int, factor2:Int, factor3:Int) -> Int{
            return factor1 * factor2 * factor3
        }
    
    }
    

    Here there are two different methods, with different names, multiply(factor2) and multiply(factor2 factor3).

    This rule only apply to methods, if you declare this like a functions outside of a class, then the function call don't require parameter name.

    0 讨论(0)
  • 2020-11-27 11:01

    The parameter names in the function call are called keyword names, and they are trace their roots back to the Smalltalk language.

    Classes and objects are often re-used from somewhere else, or form part of very large complex systems, and will not have active maintenance attention for long periods at a time.

    Improving the clarity and legibility of the code is very important in these situations, as code often ends up as the only documentation, when developers are under deadline pressure.

    Giving each parameter a descriptive keyword name allows maintainers to quickly see what the purpose of a function call by glancing at the function call, as opposed to delving deeper into the function code itself. It makes the implied meaning of the parameters explicit.

    The latest language to adopt keyword names for parameters in function calls is Rust (link) - described as "a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety."

    High uptime systems require greater code quality. Keyword names allow development and maintenance teams much more opportunity to avoid and to catch errors from sending the wrong parameter, or calling parameters out of order.

    They can be wordy or terse, but Smalltalkers prefer wordy and descriptive to terse and meaningless. They can afford to be, because their IDE will do the bulk of such typing for them.

    0 讨论(0)
  • 2020-11-27 11:13

    The reason is historical. This is how it worked in Smalltalk and it survived into its descendants. Squeak, Scratch, Blockly, Objective C and Swift.

    The kiddy languages (Squeak, Scratch and Blockly) held to it, because beginning programmers tend to struggle with the arity and parameter order. That was the original reason why Smalltalk did it that way. I do not know why ObjC and Swift decided to adopt the convention, but they did.

    0 讨论(0)
  • 2020-11-27 11:18

    A note about passing in a method as an argument that returns no value:

    func refresh(obj:Obj, _ method: (Obj)->Void = setValue) {
        method(element)
    }
    func setValue(obj:Obj){
        obj.value = "someValue"
    }
    refresh(someObj,setValue)
    
    0 讨论(0)
  • 2020-11-27 11:19

    Update for Swift 2.0: Now functions behave identically to methods, and for both, by default:

    • the first parameter has no external name; and
    • the other parameters have an external name identical to the internal name.

    Other than that, the rules below still apply, except that the # shorthand syntax is now gone.


    Here's a more general answer: functions behave differently when defined as true functions outside a class, and when defined as methods. Moreover, init methods have a special rule.


    Functions

    Suppose you define this:

    func multiply1(f1: Double, f2: Double) -> Double {
        return f1 * f2
    }
    

    Parameter names are here only local to the function, and cannot be used when calling the function:

    multiply1(10.0, 10.0)
    

    If you want to force using named parameters when calling the function, you can. Prefix each parameter declaration with its external name. Here, the external name of f1 is f1param, and for f2, we use the shorthand where we prefix it by # to indicate that the local name is to be used as the external name as well:

    func multiply2(f1param f1: Double, #f2: Double) -> Double {
        return f1 * f2
    }
    

    Then, named parameters must be used:

    multiply2(f1param: 10.0, f2: 10.0)
    

    Methods

    Things are different for methods. By default, all but the first parameter are named, as you've discovered. Suppose we have this, and consider the multiply1 method:

    class Calc {
        func multiply1(f1: Double, f2: Double) -> Double {
            return f1 * f2
        }
        func multiply2(f1param f1: Double, f2: Double) -> Double {
            return f1 * f2
        }
        func multiply3(f1: Double, _ f2: Double) -> Double {
            return f1 * f2
        }
    }
    

    Then, you have to use the name of the second (and following, if any) parameters:

    let calc = Calc()
    calc.multiply1(1.0, f2: 10.0)
    

    You can force to use a named param for the first argument by providing an external name for it, like for functions (or prefixing its local name with # if you want to use the same external name as its local name). Then, you have to use it:

    calc.multiply2(f1param: 10.0, f2: 10.0)
    

    Finally, you can declare an external name of _ for the other following arguments, indicating that you want to call your method without using named parameters, like this:

    calc.multiply3(10.0, 10.0)
    

    Interoperability note: If you prefix class Calc with the @objc annotation, then you can use it from Objective-C code, and it is equivalent to this declaration (look at parameter names):

    @interface Calc
    - (double)multiply1:(double)f1 f2:(double)f2;
    - (double)multiply2WithF1param:(double)f1 f2:(double)f2;
    - (double)multiply3:(double)f1 :(double)f2;
    @end
    

    Init Methods

    The rule differs a bit for init methods, where all parameters have an external name by default. For instance, this works:

    class Calc {
        init(start: Int) {}
        init(_ start: String) {}
    }
    
    let c1 = Calc(start: 6)
    let c2 = Calc("6")
    

    Here, you have to specify start: for the overload that accepts an Int, but you must omit it for the overload that accepts a String.

    Interoperability note: this class would get exported to Objective-C like this:

    @interface Calc
    - (instancetype)initWithStart:(NSInteger)start __attribute__((objc_designated_initializer));
    - (instancetype)init:(NSString *)start __attribute__((objc_designated_initializer));
    @end
    

    Closures

    Assume you define a closure type like this:

    typealias FancyFunction = (f1: Double, f2: Double) -> Double
    

    The parameter names will behave very similar to those in a method. You will have to provide the names to the parameters when calling the closure unless you explicitly set the external name to _.

    For example, executing the closure:

    fund doSomethingInteresting(withFunction: FancyFunction) {
        withFunction(f1: 1.0, f2: 3.0)
    }
    

    As a rule of thumb: even if you dislike them, you should probably try to keep using named parameters at least whenever two parameters have the same type, in order to disambiguate them. I'd also argue that it's good to also name at least all Int and Boolean parameters.

    0 讨论(0)
提交回复
热议问题