In the following cases, the parameter name is required when calling a swift function
   
  
   
    
1. when defining a regular function without external parameter name, the caller does not specify the first parameter's name, but need to specify all following parameter's name
    func join0(string: String, toString: String, withJoiner: String) -> String {
        return string + toString + withJoiner
    }
    join0("hello", toString: "world", withJoiner: ", ")
2. if the function's first as well as other parameters have external names, (internal name and external name are indicated by a space),
   
    func join1(string s1: String, toString s2: String, withJoiner: String) -> String {
        return s1 + withJoiner + s2
    }
    join1(string: "hello", toString: "world", withJoiner: ", ")
3. if the function's first parameters starts with '#', it indicates internal name and external name are same
    func join2(#string: String, toString: String, withJoiner: String) -> String {
        return s1 + joiner + s2
    }
    join1(string: "hello", toString: "world", withJoiner: ", ")
4. if the function's first parameters has default value, the caller must specify the parameter name to call it
    func join3(string: String ="abc", toString: String, withJoiner: String) -> String {
        return s1 + joiner + s2
    }
    join3(string: "hello", toString: "world", withJoiner: ", ") 
 5.In any case, if the parameter's external name is '_', then caller does not need specify the parameter's name,
    func join4( _ string: String = "abc", _ toString: String, _ withJoiner: String) -> String {
        return string + withJoiner + toString
    }
       join4("hello", "world", ", ")
      Sometimes, if a parameter has a default value, but does not want to have an external name, then, explicitly specify '_' as external parameter name as shown below:
- func join(s1: String, s2: String, _ joiner: String = " ") -> String {
- return s1 + joiner + s2}
- join("hello", "world", "-")
No comments:
Post a Comment