Function parameter error - Missing Argument Label Anomaly - SWIFT - xcode

I have a strange issue (which I can overcome however I would like to get a proper understanding of my error).
I have a small random number generator function which I use often:
func ranNum(low: Int, high:Int) -> UInt32 {
var result = arc4random_uniform(UInt32((high+1)-low)) + low
return result
}
When I use this in XCode playgrounds it works just fine if I pass in something like:
ranNum(1, 10)
However, in a regular Swift file it generates the error message : Missing argument label 'hi:' in call. Now I can overcome this by calling the function this way:
ranNum(1, hi:10)
Apart from it just being a little harder to read, it just isn't making sense why it works in Playgrounds but also why it requires only the 2nd argument label and not both. Any help as to what I am not understandinh would be greatly appreciated.

That's called external parameter name, and by default:
global functions: don't have implicit external names
class/struct methods: external names are automatically defined for all parameters after the first
initializers: external names are automatically defined for all parameters
If not explicitly specified, external names take the same name as the local parameter.
You can override that by prefixing a local parameter name with _. In your case:
func ranNum(low: Int, _ high:Int) -> UInt32 {
...
}
You mentioned that in playground calling the function works without any external parameter name - I may argue that:
in playground you have that function as a global function
in other tests, that function is a class/struct method
Am I right?

Related

linter err113: do not define dynamic errors, use wrapped static errors instead

I am using err113 as part of golangci-lint.
It is complaining about ...
foo_test.go:55:61: err113: do not define dynamic errors, use wrapped static errors instead: "errors.New(\"repo gave err\")" (goerr113)
repoMock.EXPECT().Save(gomock.Eq(&foooBarBar)).Return(nil, errors.New("repo gave err")),
^
foo_test.go:22:42: err113: do not define dynamic errors, use wrapped static errors instead: "errors.New(\"oops\")" (goerr113)
repoMock.EXPECT().FindAll().Return(nil, errors.New("oops"))
^
What is best way to fix this ?
Quoting https://github.com/Djarvur/go-err113
Also, any call of errors.New() and fmt.Errorf() methods are reported
except the calls used to initialise package-level variables and the
fmt.Errorf() calls wrapping the other errors.
I am trying to get a idiomatic example for this.
Declare a package-level variables as suggested:
var repoGaveErr = errors.New("repo gave err")
func someFunc() {
repoMock.EXPECT().Save(gomock.Eq(&foooBarBar)).Return(nil, repoGaveErr)
}
Every call to errors.New allocates a new unique error value. The application creates a single value representing the error by declaring the package-level variable.
There are two motivations for the single value:
The application can compare values for equality to check for a specific error condition.
Reduce memory allocations (although probably not a big deal in practice)
The value io.EOF is a canonical example.
Since GO 1.13 you can define a new error type, wrap it and use it.
for example, if you want to return an "operation not permitted" + the operation.
you need to implement something like
var OperationNotPermit = errors.New("operation not permitted")
func OperationNotFoundError(op string) error {
return fmt.Errorf("OperationNotPermit %w : %s", OperationNotPermit, op)
}
then in your code, when you want to return the error,
return nil, OperationNotFoundError(Op)
Let's back to question case:
first, define the custom error and the wapper
var repoError = errors.New("repositoryError")
func RepositoryError(msg string) error {
return fmt.Errorf("%w: %s", repoError,msg)
}
then in your code,
repoMock.EXPECT().Save(gomock.Eq(&foooBarBar)).Return(nil, RepositoryError("YOUR CUSTOM ERROR MESSAGE"))
Since it hasn't been said before, you probably don't need to define package level errors for tests. Given the idea is to wrap errors so they can be compared and unwrapped in the caller, returning a dynamic error in a test is fine as long as the purposes of your test are served.

Function defines unnamed parameters but caller still passes values

I'm trying to understand the Wire library in Golang and find that in the wire.go there's a function looks like this:
func NewSet(...interface{}) ProviderSet {
return ProviderSet{}
}
It looks foreign to me as to why the ...interface{}) parameter is unnamed (meaning not being used inside the function) but then the caller still passes meaningful values to it?
var Set = wire.NewSet(
wire.Value(Foo(41)),
provideFooBar)
Parameters being named or unnamed has nothing to do with whether the caller having to pass values for them. Being unnamed just means they cannot be used (cannot be referred to) inside the function.
NewSet has a variadic parameter, which means any number of arguments may be passed to it that can be assigned to the type, and any value can be assigned to interface{} (all value implements the empty interface).
The "empty" implementation of NewSet() you see is just a placeholder for documentation and compilers. The generated code will use the passed arguments.
If you have a function:
func dummy(int) {}
You can't call it like dummy(), that's a compile-time error. You can only call it by passing an int value to it, e.g. dummy(1).
See related: Is unnamed arguments a thing in Go?

What does it mean to pass `_` (i.e., underscore) as the sole parameter to a Dart language function?

I'm learning Dart and see the following idiom a lot:
someFuture.then((_) => someFunc());
I have also seen code like:
someOtherFuture.then(() => someOtherFunc());
Is there a functional difference between these two examples?
A.k.a., What does passing _ as a parameter to a Dart function do?
This is particularly confusing given Dart's use of _ as a prefix for declaring private functions.
It's a variable named _ typically because you plan to not use it and throw it away. For example you can use the name x or foo instead.
The difference between (_) and () is simple in that one function takes an argument and the other doesn't.
DON’T use a leading underscore for identifiers that aren’t private.
Exception: An unused parameter can be named _, __, ___, etc. This
happens in things like callbacks where you are passed a value but you
don’t need to use it. Giving it a name that consists solely of
underscores is the idiomatic way to indicate the value isn’t used.
https://dart.dev/guides/language/effective-dart/style
An underscore (_) is usually an indication that you will not be using this parameter within the block. This is just a neat way to write code.
Let's say I've a method with two parameters useful and useless and I'm not using useless in the code block:
void method(int useful, int useless) {
print(useful);
}
Since useless variable won't be used, I should rather write the above code as:
void method(int useful, int _) { // 'useless' is replaced with '_'
print(useful);
}
From the Dart Doc - PREFER using _, __, etc. for unused callback parameters.
Sometimes the type signature of a callback function requires a
parameter, but the callback implementation doesn't use the
parameter. In this case, it's idiomatic to name the unused parameter
_. If the function has multiple unused parameters, use additional
underscores to avoid name collisions: __, ___, etc.
futureOfVoid.then((_) {
print('Operation complete.');
});
This guideline is only for functions that are both anonymous and
local. These functions are usually used immediately in a context
where it's clear what the unused parameter represents. In contrast,
top-level functions and method declarations don't have that context,
so their parameters must be named so that it's clear what each
parameter is for, even if it isn't used.
Copy paste the following code in DartPad and hit Run -
void main() {
Future.delayed(Duration(seconds: 1), () {
print("No argument Anonymous function");
});
funcReturnsInteger().then((_) {
print("Single argument Anonymous function " +
"stating not interested in using argument " +
"but can be accessed like this -> $_");
});
}
Future<int> funcReturnsInteger() async {
return 100;
}
That expression is similar to "callbacks" in node.js, the expression have relation to async task.
First remember that => expr expression is shorthand for {return *expr*}, now in someFuture.then((_) => someFunc()), someFuture is a variable of type Future, and this keeps your async task, with the .then method you tell what to do with your async task (once completed), and args in this method you put the callback ((response) => doSomethingWith(response)).
You learn more at Future-Based APIs and Functions in Dart. Thanks
Very common use, is when we need to push a new route with Navigator but the context variable in the builder is not going to be used:
// context is going to be used
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => NewPage(),
));
// context is NOT going to be used
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => NewPage(),
));
I think what people are confusing here is that many think the _ in
someFuture.then((_) => someFunc());
is a parameter provided to the callback function which is wrong, its actually a parameter passed back from the function that you can give a name that you want (except reserved keywords of course), in this case its an underscore to show that the parameter will not be used. otherwise, you could do something like in example given above:((response) => doSomethingWith(response))

What are these method parameters called in Swift?

I'm just taking my first steps with Swift and after having worked with things like PHP, Ruby, JavaScript and Python, this is all totally new to me.
So, I have code like this:
class DerpController: NSURLConnectionDelegate, NSURLConnectionDataDelegate {
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse) {
println("response received")
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
println("data received")
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println("request finished")
}
}
What are these things called: didReceiveResponse, didReceiveData? Are they some kind kind of message identifier or what?
And is func connection one overloaded method or are there actually two that are identified by these "didReceive..." names?
didReceiveResponse is an external parameter name. response and data are local parameter names.
This means that the first function is called with myDerpController.connection(url, didReceiveResponse:response). But within the body of the function you refer to the parameter as response.
The second function is a typo, and should be didReceiveData
These are delegate methods defined by NSURLConnectionDataDelegate, which is a protocol you have adopted.
In Swift, a parameter can have both an internal (parameter, local) name and an external (argument, caller) name. The internal name (response:, data:) is entirely up to you; the name provided by the docs and by code completion is just a "serving suggestion". The external name, however, needs to match the selector name by which Objective-C (or any other caller) will seek it. The method is called e.g. connection:didReceiveData: so you must use an external name didReceiveData for the second parameter in order to be called.
You also asked (irrelevantly) about overloading. Overloading by type is legal in Swift but not in Objective-C; the latter uses names (selectors) alone. You're biting off a lot at once here because you've chosen to start with an example involving heavy interplay between Swift and Objective-C, to understand which you really need to know at least the rudiments of both languages.

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

I have this Function in a class:
func multiply(factor1:Int, factor2:Int) -> Int{
return factor1 * factor2
}
I try to call the function using this:
var multResult = calculator.multiply(9834, 2321)
The problem is that the compiler wants it to look more like this:
var multResult = calculator.multiply(9834, factor2: 2321)
Why does the first one cause an error?
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.
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.
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);
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.
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.
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)

Resources