Difference between two function calls - Swift - swift

What is the difference between these two Swift functions. I don't quite understand it. I know they are two different functions but they have different parameter structures.
func addTwoIntegers(first x:Int, second y:Int) -> Int{
return x + y
}
func multiplyTwoIntegers(x:Int, y:Int) -> Int{
return x * y
}

The difference between the two functions are evident if you use them inside of Swift’s playground. The first function uses external naming parameters which allow you to see the name of the parameters in kind of an Objective-c style fashion. For example, when I call addTwoIntegers, I will be able to call it like this while passing in the arguments addTwoIntegers(first: x, second: y). The second function does not use external naming parameters so you can only call it passing in the arguments such as multiplyTwoIntegers(2,2)
Copy this code into Xcode’s playground.
func addTwoIntegers(first x:Int, second y:Int) -> Int{
return x + y
}
func multiplyTwoIntegers(x:Int, y:Int) -> Int{
return x * y
}
var x = addTwoIntegers(first: 10, second: 10)
var y = multiplyTwoIntegers(2, 2)
println(x)
println(y)

The first uses externally named parameters as well as local parameter names and the second uses just locally name parameters

Related

Swift function parameters as local variables

I am learning some of the fine point of Swift. On function parameters, the documentation says:
Function parameters are constants by default.
… and proceeds to discuss in-out parameters, which I suppose are Swift’s version of reference parameters.
In other languages, parameters behave as local variables, so you can do this with impunity:
func test(a: Int) {
a = a + 1 // cannot assign to a
print(a*2)
}
var x = 3
test(x)
print(x) // -> 3 as before
I know I can easily create local variables, but is there a Swift equivalent to parameters as local variables?
Note:
The SO description for the parameter tag even uses the word “label”:
Parameters are a type of variable used in a subroutine to refer to the data provided as input to the subroutine.
Before Swift 3, Swift used to have them. You used to be able to do something like this:
func f(var x: Int) { // note the "var" modifier here
x += 1
print(x) // prints 2
}
var a = 1
f(a)
print(a) // prints 1
But it was removed in Swift 3, via SE-0003. The Swift community decided that this is not a good feature. The motivations given in that proposal are:
var is often confused with inout in function parameters.
var is often confused to make value types have reference semantics.
Function parameters are not refutable patterns like in if-, while-, guard-, for-in-, and case statements.
Not sure I understood what do you try to achieve, but if you want to modify external x (so it would be not 3 as before), then you have to make function parameter as inout:
func test(_ a: inout Int) {
a = a + 1 // no error anymore
print(a*2)
}
var x = 3
test(&x)
print(x) // -> 4
Update:
func test(_ a: Int) {
var a = a // make read-write
a = a + 1
print(a*2)
}
var x = 3
test(x)
print(x) // -> 3 as before

Inconsistent operator overload resolution when using operators with "function style" syntax ('(binaryOp)(lhs, rhs)', and '(unaryOp)(operand)')

Question (/TL;DR)
In the details below we see that using function style ((unaryOperator)(operand), (binaryOperator)(lhsOperand, rhsOperand)) syntax to call operator functions seemingly override the type checker's normal overload resolution rules; the the overload simply picks the first (in order of definition) overload that it can find.
Is this a bug? Or is this some peculiar but expected behaviour of the call-operator-by-function-style ((unaryOperator)(operand), (binaryOperator)(lhsOperand, rhsOperand)) syntax?
Background
I just read Matt Gallagher's excellent post on some current issues with the Swift type checker
Exponential time complexity in the Swift type checker
One of the issues raised in the article is the problems that can follow from the fact that generic overloads are not considered in the overload resolution of operators, given that non-generic alternatives exist. Gallagher shows one such "issue" with the following example
/* note: Swift 3 */
prefix operator %% {}
prefix func %%(_ x: Float) -> Float { return x }
prefix func %%<I: Integer>(_ x: I) -> I { return x }
let y = %%1 // integer literal
print(y.dynamicType) // "Float"
We naturally see the same result if we switch places on the two %% operator definitions above, i.e.
/* ... same result as above */
prefix operator %% {}
prefix func %%<I: Integer>(_ x: I) -> I { return x }
prefix func %%(_ x: Float) -> Float { return x }
Note also that the above strictly non-generic precedence for overload resolution is not present for functions, as shown by Gallagher with the following example
/* resolves x to "Int", no matter the order
of these two function definitions */
func f(_ x: Float) -> Float { return x }
func f<I: Integer>(_ x: I) -> I { return x }
let x = f(1)
print(x.dynamicType) // "Int"
Further details pertaining the question
Now on to the peculiarity. We may call binary and unary operations in function style using the (binaryOperator)(lhsOperand, rhsOperand) and (unaryOperator)(operand) syntax, respectively. E.g.
let a = (+)(1, 2) // 3
let b = (-)(a) // -3
Now, if we apply this syntax to the %% operator example above, the overload resolution rules as described above seems to no longer apply (no matter if we were to regard this as a function call or an operator call), as the type of y in the example above seemingly depends solely on the order in which the %% definitions appear.
prefix operator %% {}
prefix func %%(_ x: Float) -> Float { return x }
prefix func %%<I: Integer>(_ x: I) -> I { return x }
let y = (%%)(1)
print(y.dynamicType) // "Float"
/* swap the order of the definitions ... */
prefix operator %% {}
prefix func %%<I: Integer>(_ x: I) -> I { return x }
prefix func %%(_ x: Float) -> Float { return x }
let y = (%%)(1)
print(y.dynamicType) // "Int"
We may even, for some special conditions†, introduce additional overloads that (expectedly) yields ambiguity for the normal %%1 case, where the function style (%%)(1) case compiles without ambiguity, picking the first definition it can find.
prefix operator %% {}
prefix func %%(_ x: Double) -> Double { return x }
prefix func %%<I: Integer>(_ x: I) -> I { return x }
prefix func %%(_ x: Float) -> Float { return x }
// picks first %% definition it can find
let y = (%%)(1)
print(y.dynamicType) // "Double"
// ambiguity error as expected
//let z = %%(1) // error: ambiguous use of operator '%%'
[†]: The non-error behaviour of this last example is really unreliable: if we e.g. introduce a 2nd generic overload, the snippet runs only without error if a non-generic overload is defined first, but moreover only if a generic overload definition follows that non-generic one. I wont dwell further, however, into that special-case madness, but it seems like some "peek" behaviour: accepting a first defined non-generic overload given that a peek of the next definition shows a generic one.
(Tested for Swift 3.0 in the IBM Swift Sandbox. Swift 2.2 adapted version tested in XCode 7.3 playground as well as in a project)

Is it possible to call a function as a parameter of another function in Swift?

Is it possible to call a function as a parameter of another function in Swift??
I am making a sound effects app in Swift which uses different effects like AVAudioUnitReverb() and AVAudioUnitDistortion() etc. I wanted to create a single function and just be able to call which effects I wanted to do.
Because in Swift functions are first-class types, you can pass it as an argument to another function.
Example:
func testA() {
print("Test A")
}
func testB(function: () -> Void) {
function()
}
testB(testA)
You can pass in functions as parameter my typing the parameter with the same signature.
As sunshine's example just deals with Void parameters and return types, I want to add another example
func plus(x:Int, y:Int) -> Int {
return x + y
}
func minus(x:Int, y:Int) -> Int {
return x - y
}
func performOperation (x:Int, _ y:Int, op:(x:Int,y: Int) -> Int) -> Int {
return op(x: x, y: y)
}
let resultplus = performOperation(1, 2, op: plus) // -> 3
let resultminus = performOperation(1, 2, op: minus) // -> -1
note: Of course you should consider dynamic typed parameters. For simplicity here just Ints
this is called Higher Order Functions and in many languages this is the way of doing it. But often you don't won't to explicitly create functionss for it. Here Closures are a perfect tool:
The function performOperation stays untouched, but the operations are implemented differently:
let plus = { (x:Int, y:Int) -> Int in
return x + y
}
let minus = { (x:Int, y:Int) -> Int in
return x - y
}
let resultplus = performOperation(1, 2, op: plus)
let resultminus = performOperation(1, 2, op: minus)
Often this would be preferred as it doesn't need methods to be added to a class, pretty much like anonymous functions in other languages.
More on this and how it is used in the swift standard library: https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/
I would recommend book "IOS 9 Programming Fundamentals with Swift" by Matt Neuburg, especially subchapter "Functions".
You should not only find the answer for your question:
func imageOfSize(size:CGSize, _ whatToDraw:() -> ()) -> UIImage {
...
}
But also how to construct function that returns the function:
func makeRoundedRectangleMaker(sz:CGSize) -> () -> UIImage {
...
}
As well as brief introduction to Curried Functions.

Translating Swift Into English

I'm attempting to teach myself to code in Swift but I'm having a difficult time translating what I'm reading into something that resembles English. Here's an example:
func createAdder(numberToAdd: Int) -> (Int) -> Int
{
func adder(number: Int) -> Int
{
return numberToAdd + number
}
return adder
}
var addTwo = createAdder(2)
addTwo(4)
How do I read that first line of code and can you explain how this function is executed?
createAdder is a function that returns a function. The placement of the parentheses is a little off-putting - it makes more sense like this:
func createAdder(numberToAdd: Int) -> (Int -> Int)
So it returns a function of type Int -> Int. What does that mean? Take a look at this function:
func addTwo(n: Int) -> Int {
return n + 2
}
That function takes an integer - n - and returns another integer. So the type of the function is:
Int -> Int
In this case, this function just adds two to whatever it was given. But say you wanted to generalise (it doesn't make much sense in this contrived example, but this kind of thing is very powerful in other scenarios). Say you wanted to have a bunch of functions, each of them adding a number to a number they were given. To do that, you'd need to write something like what you've written in your example:
func createAdder(numberToAdd: Int) -> (Int) -> Int
{
func adder(number: Int) -> Int
{
return numberToAdd + number
}
return adder
}
The createAdder function takes a number, and then defines a new function - adder - which it returns.
The final bit that might be confusing is the line
var addTwo = createAdder(2)
Usually, you define functions with the word func. However, that's just syntax. Functions are variables just like every other type in Swift, and they can be treated as such. That's why you're able to return a function, and that's why you're able to assign it using var.
So what does it do? Well, if you call createAdder(2), what you get back is equivalent to
func addTwo(n: Int) -> Int {
return n + 2
}
If you did something like:
var addThree = createAdder(3)
It would be equivalent to:
func addThree(n: Int) -> Int {
return n + 3
}
And in both cases, you'd use them just like normal functions:
addThree(1) // returns 4
So I said the example was a little contrived - and it is - so where would this kind of thing be useful? In general, functions that either take or return functions are called "higher-order" functions. They're massively useful, and if you go down the functional programming route they can get very powerful and a bit philosophical pretty quickly. Keeping it grounded, the first place most people come across them in Swift is with the function .map(). map() is a higher-order function - it takes a function as its parameter. However, it also takes something else - in this example, it's going to be an array. What it does is apply the function it's given to every element of the array. So, let's use the createAdder() to give us a function that adds 1 to a number:
let addOne = createAdder(1)
Right, then let's get an array of other numbers:
let nums = [1, 2, 3, 4]
Then, let's put it all together with map:
let mapped = nums.map(addOne) // [2, 3, 4, 5]
As you can see, that's a pretty powerful way to process and manage arrays. There's a whole host of functions like this - filter(), flatMap(), reduce() - and they all rely on this concept.
It reads: declare a function named "createAdder" that takes an Int as an argument, this function returns a function which itself takes an Int as an argument; and this function itself, what is returned from "createAdder", returns an Int.
-> (Int) -> Int
means "returns a function -taking an Int- which will return an Int".
The first line of code reads:
A function createAdder that takes as an argument a numberToAdd of type Integer and returns a function that receives an Integer as an argument and returns an Integer. In this case, the function that is returned is the adder function that is created within the createAdder.

Accessing number of parameters in a closure in Swift

Suppose I have a function:
func test(closure: (closureArgs: Double ...) -> Double){
//some logic
}
Then later, I call it with:
test({$0 + $1 + $2 + $3})
Is it possible to get the number of closureArgs provided within test? The goal would be to do overloading. For example, test could include some code like:
func test(closure: (closureArgs: Double ...) -> Double){
//somehow get access to number of arguments in closureArgs within the closure that was passed.
}
To clarify - I mean I need to access closureArgs's length INSIDE test but OUTSIDE closure
Is it possible to get the number of closureArgs provided within test?
The Short Answer
No.
Slightly Longer Answer
No, it is not. Here's why:
The function is taking a closure as it's argument that by definition takes a variadic number of arguments. There's no possible way for someone calling the function to designate how many arguments the closure should take ahead of time. For example, if I were to call your function, it might look like this:
test() { (closureArgs: Double...) -> Double in
var n: Double = 0
for i in closureArgs {
n += i
}
return n
}
As you'll notice, I don't define the number of arguments anywhere because the number of arguments is only specified when the closure is called. Then the number can be determined inside, or possibly returned.
Basically, the closure is called within test, so only you the caller know how many arguments it takes. Anyone consuming this function has no control over it.
The only way I can think of is to have the closure return a tuple that contains the number of arguments and a function that gives the answer, like this:
func test(c: (Double...) -> (Int, (Double...) -> Double)) {
let (argCount, function): (Int, (Double...) -> Double) = { c($0) }()
switch argCount {
// do something with function here
}
}
func sum(a: Double...) -> (Int, ((Double...) -> Double)) {
return (a.count, { reduce(a, 0, +) })
}
Something like that might work, but I'm not in a place where I can test it.
Edit: I'm trying to test this now, and it's close, but it doesn't work yet...
Edit: Okay, this works, but maybe not in the way that you want...
func test(c: (Int, Double)) {
let (argCount, result) = c
switch argCount {
case 2:
println("2 args were passed")
println("The result was \(result)")
default:
println("nothing")
}
}
func sum(a: Double...) -> (Int, Double) {
return (a.count, reduce(a, 0, +))
}
Now test(sum(2, 4)) will print that the number of arguments was 2 and the result was 6.
The thing is, when you are passing a closure that already has arguments supplied (and it needs arguments to know how to calculate the count) then you're closure function already evaluates to a result. So have the closure return the number of arguments that it used to calculate the result along with the result. Then in test you can work with both the number of arguments and the result.
I don't know...it's hard to know exactly what you are after because I'm not sure what kind of logic you need to implement once you know the number of arguments...
Edit: Sorry I keep going on and on, but it seems like you know how many arguments are going to be included when you call test, right? I mean, in your example you supplied 4 arguments:
test({$0 + $1 + $2 + $3})
(Although, you really need to rewrite that as:
test({ return $0[0] + $0[1] + $0[2] + $0[3] })
...cuz remember, variadic parameters are passed as an array...)
So if you know how many arguments are going to be in the closure when you pass it to test, just include the number of arguments as a parameter in test, like this:
func test(count: Int, closure: (Double...) -> Double) {
switch count {
case 1:
// do what you want if there is only one argument
case 2:
// do what you want if there are two arguments...etc.
}
}
Now when you call test, you just pass the number of arguments as an Int:
test(4, { return $0[0] + $0[1] + $0[2] + $0[3] })
In other words, you always know how many arguments you are passing to the closure when you pass it. If you want test to know, just include that as a parameter.
The answer goes back to how Swift passes arguments to varargs functions, which is as an array. Generally speaking, the function definition:
func takesVarArgs(args: Double...)
Is syntactic sugar, providing for simpler invocation, for the declaration:
func takesVarArgs(args:[Double])
So, in your case, your closure will be invoked as:
func test(closure: (closureArgs:[Double]) -> Double)) -> Double
Then, within your closure you could get the number of arguments with:
closureArgs.count