Extraneous argument label 'number:' in call - swift

While I was learning about "Functions", I met an issue showing "Extraneous argument label 'number:' in call" error msg for my code. I wonder why I shouldn't place "number" in argument?
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(number: 7)
enter image description here

The problem is that you're returning a (Int) -> Int, which doesn't specify a name for its argument. Ideally, you'd want to write
func makeIncrementer() -> ((number: Int) -> Int)
but that isn't allowed in Swift:
function types cannot have argument labels; use '_' before 'number'
The best you can do is
func makeIncrementer() -> ((_ number: Int) -> Int)
This strategy might make your code a little clearer because giving the argument a name makes its purpose more obvious. Unfortunately, you still have to omit the number: label when you call the returned function:
let increment = makeIncrementer()
increment(7) // <- no `number:` label
What's the rationale?
Specifying argument labels for function types was possible before Swift 3. The problem was that you could write
func add(numToAdd: Int) -> Int { ... }
func subtract(numToSubtract: Int) -> Int { ... }
let f: ((numToAdd: Int) -> Int) = subtract
and then calling f(numToAdd: 3) would actually call subtract(numToSubtract: 3), which is quite surprising and can cause confusion.
Check out this proposal for the full rationale behind removing this feature.

Related

Can't find variable name in scope

I am trying to learn Swift and I have bought a book to help me learn the language.
I can't understand why the following does not work:
func sum(_a: Int, _b: Int) -> Int {
return a + b
}
func subtract(_a: Int, _b: Int) -> Int{
return a - b
}
var someFunc: (Int, Int) -> Int
someFunc = sum
print(someFunc(5, 4))
someFunc = subtract
print(someFunc (5, 4))
The error I get is Cannot find 'a' (or 'b') in scope.
If I remove the underscores it does give the right answer.
I thought the point of the underscore was that the underscore meant that nothing is assigned to it and the function you want to call that returns a result but you don't care about the returned value.
Can somebody explain in simple language why this does not work.
You have to put a space between _ a, _ b. Like this:
func sum(_ a: Int, _ b: Int) -> Int {
return a + b
}
func subtract(_ a: Int, _ b: Int) -> Int{
return a - b
}
var someFunc: (Int, Int) -> Int
someFunc = sum
print(someFunc(5, 4))
someFunc = subtract
print(someFunc (5, 4))
You can learn these functions in a Playground. You will see there errors, etc...
The underscore means that the parameter will not have a label when calling then function making it more compact.
Below is 3 different ways to use labels for parameters when creating a function
Function with anonymous (no label) parameters
func example1(_ a: Int, _ b: Int) -> Int {
a + b
}
let sum = example1(3, 5)
Function with parameters as labels
func example2(a: Int, b: Int) -> Int {
a + b
}
let sum = example2(a: 3, b: 5)
Function with different parameter names and labels
func example3(first a: Int, second b: Int) -> Int {
a + b
}
let sum = example3(first: 3, second: 5)
When declaring functions in Swift, you can provide names for parameters passed to a function. It is handy to make your functions more readable when using in code. E.g. you can declare it like so:
func move(from startPoint: Int, to endPoint: Int) -> Int {
return startPoint + endPoint
}
In your function's body you can use variables' names, which is quite understandable for you. And usage of your functions will look like:
res = move(from: 1, to: 2)
I this way it will be more readable for any person who will read or use your code. It will be more clear even for you, when you'll return to this code some time later.
You can also declare the function in the way not to show any variables' names at all. For this you can use "_" as a variable's name. And this is the case from your learning book.
Guys have already answered your question. I just wanted to give you a bit deeper understanding.

Cannot convert value of type 'Range<Int>' to expected argument type 'Range<_>'

Using Swift 4.2, I get the title as an error in this function:
func jitter(range: Int) -> Int {
return Int.random(in: 0..<range, using: SystemRandomNumberGenerator())
}
Questions:
What precisely does Range<_> mean?
Is there a better way to get this? I simply want a small random number inside an animation loop.
The Swift compiler is giving you a bad error message. The problem is that the second argument to Int.random(in:using:) must be passed inout (i.e. with a & prefix). This works:
func jitter(range: Int) -> Int {
var rng = SystemRandomNumberGenerator()
return Int.random(in: 0..<range, using: &rng)
}
Even easier, omit the using: parameter altogether (SystemRandomNumberGenerator is the default RNG anyway):
func jitter(range: Int) -> Int {
return Int.random(in: 0..<range)
}

Why does use of closure shorthand-named variables has to be exhaustive in a singular return expression in Swift?

The following piece of code are erroneous in Swift.
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {$0}))
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {return $0}))
The error given by XCode playground is Cannot convert value of type '(Int, Int)' to closure result type 'Int'.
While the following pieces of code are completely fine.
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {$0 + $1}))
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {$1; return $0}))
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {a, b in a}))
It seems that in a situation where arguments to a closure are referred to by shorthand argument names, they must be used exhaustively if the the body of the closure only consists of the return expression. Why?
If you just use $0, the closure arguments are assumed to be a tuple instead of multiple variables $0, $1 etc. So you should be able to work around this by extracting the first value of that tuple:
print(foo(closure: {$0.0}))
Your "why" is like asking "why is an American football field 100 yards long?" It's because those are the rules. An anonymous function body that takes parameters must explicitly acknowledge all parameters. It can do this in any of three ways:
Represent them using $0, $1, ... notation.
Represent them using parameter names in an in line.
Explicitly discard them by using _ in an in line.
So, let's take a much simpler example than yours:
func f(_ ff:(Int)->(Void)) {}
As you can see, the function f takes one parameter, which is a function taking one parameter.
Well then, let's try handing some anonymous functions to f.
This is legal because we name the parameter in an in line:
f {
myParam in
}
And this is legal because we accept the parameter using $0 notation:
f {
$0
}
And this is legal because we explicitly throw away the parameter using _ in the in line:
f {
_ in
}
But this is not legal:
f {
1 // error: contextual type for closure argument list expects 1 argument,
// which cannot be implicitly ignored
}

Method signature in Swift [duplicate]

I'm new to Swift and I've been going thru some tutorials and many of them define a function more than once with the same name.
I'm used to other programming languages where this cannot be done otherwise it throws an error.
Therefore I've checked the official Swift Manual and also checked the override keyword to see what I could get out of it, but still I cannot understand the following code:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
cell.textLabel?.text = "Row #\(indexPath.row)"
cell.detailTextLabel?.text = "Subtitle #\(indexPath.row)"
return cell
}
From what I can see the function tableView is set in line #1 as well as in line #5, the only difference I noticed is that the first tableView function returns an Int and the second one returns an Object (UITableViewCell).
In this case I see from the result the second function is NOT overriding the first one.
What does this mean and why is it possible to define a function more than once with the same name without overriding it?
You are allowed to define two functions with the same name if they have different Types, or if they can be distinguished by their external parameter argument labels. The Type of a function is composed of the parameter Types in parentheses, followed by ->, followed by the return Type. Note that the argument labels are NOT a part of the function's Type. (But see UPDATE below.)
For example, the following functions both have the same name and are of Type (Int, Int) -> Int:
// This:
func add(a: Int, b: Int) -> Int {
return a + b
}
// Is the same Type as this:
func add(x: Int, y: Int) -> Int {
return x + y
}
This will produce a compile-time error - changing the labels from a:b: to x:y: does not distinguish the two functions. (But see UPDATE below.)
Using Mr. Web's functions as examples:
// Function A: This function has the Type (UITableView, Int) -> Int
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }
// Function B: This function has the Type (UITableView, NSIndexPath) -> UITableViewCell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ... }
// Function C: This made up function will produce a compile-time error because
// it has the same name and Type as Function A, (UITableView, Int) -> Int:
func tableView(arg1: UITableView, arg2: Int) -> Int { ... }
Function A and Function B above do not conflict because they are of different Types. Function A and Function C above do conflict because they have the same Type. Changing the parameter labels does not resolve the conflict if the Types remain the same. (See UPDATE below.)
override is a different concept altogether, and I think some of the other answers cover it, so I'll skip it.
UPDATE: Some of what I wrote above is incorrect. It is true that a function's parameter labels are not a part of it's Type definition, but they can be used to distinguish two functions that have the same Type, so long as the function has external labels that are different such that the compiler can tell which function you are trying to call when you invoke it. Example:
func add(a: Int, to b: Int) -> Int { // called with add(1, to: 3)
println("This is in the first function defintion.")
return a + b
}
func add(a: Int, and b: Int) -> Int { // called with add(1, and: 3)
println("This is in the second function definition")
return a + b
}
let answer1 = add(1, to: 3) // prints "This is in the first function definition"
let answer2 = add(1, and: 3) // prints "This is in the second function definition"
So, the use of external labels in a function definition will allow functions with the same name and of the same type to compile. So, it appears that you can write multiple functions with the same name so long as the compiler can distinguish them by their types or by their external signature labels. I don't think internal labels matter. (But I hope someone will correct me if I'm wrong.)
In Swift, as in Objective-C, the parameters of a function form part of the definition. There aren't two functions called tableView, there is one function called tableView(tableView:, numberOfRowsInSection:) and one called tableView(tableView:, cellForRowAtIndexPath:)
You're thinking of function overloading.
An excerpt from the Apple documentation here:
You can overload a generic function or initializer by providing
different constraints, requirements, or both on the type parameters in
the generic parameter clause. When you call an overloaded generic
function or initializer, the compiler uses these constraints to
resolve which overloaded function or initializer to invoke.
For example:
protocol A { }
protocol B { }
class A1: A { }
class A2: A { }
class B1: B { }
class B2: B { }
func process<T: A>(value: T)
{
// process values conforming to protocol A
}
func process<T: B>(value: T)
{
// process values conforming to protocol B
}
or:
func process(value: Int)
{
// process integer value
}
func process(value: Float)
{
// process float value
}
This confusion is common especially if you're migrating from Objective-C to Swift for the first time. You should read about parameter names here.
The functions aren't the same they are different . Because they don't take the same arguments and return different things . This is the simple explanation if you don't understand generics.

Parentheses in Function and Closure

I am bit confused on declaring parameter and return type in Swift.
does these parameter and return type have the same meaning? What is the use of those parentheses ()?
func myFunction() -> (()-> Int)
func myFunction() -> (Void-> Int)
func myFunction() -> Void-> Int
First... () and Void are the same thing you have two different ways of writing the same thing.
Second... The -> is right associative. So using parens as you have in your examples are meaningless, much like they are with an expression such as a + (b * c). That expression is identical to a + b * c.
Basically, the three examples in your question all define a function that takes no parameters and returns a closure that takes no parameters and returns an Int.
Some more examples to help:
func myFuncA() -> () -> Int -> String {
return { () -> Int -> String in return { (i: Int) -> String in String(i) } }
}
func myFuncB() -> () -> (Int -> String) {
return { () -> Int -> String in return { (i: Int) -> String in String(i) } }
}
func myFuncC() -> (() -> Int) -> String {
return { (f: () -> Int) in String(f()) }
}
In the above, myFuncA is identical to myFuncB, and they are both different than myFuncC.
myFuncA (and B) takes no parameters, and returns a closure. The closure it returns takes no parameters and returns another closure. This second closure takes an Int and returns a String.
myFuncC takes no parameters and returns a closure. The closure it returns takes a closure as a parameter and returns a String. The second closure takes no parameters and returns an Int.
Hopefully, writing it in Prose hasn't made it even more confusing.