SLN SLN - 1 year ago 104
Swift Question

If a constant variable is a type of function type, then what cannot be changed?

The code used here comes from the Swift Official Document

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0

func incrementer() -> Int {
runningTotal += amount
return runningTotal
return incrementer

// what is the different with "var incrementByTen"
let incrementByTen = makeIncrementer(forIncrement: 10)

// why there is a "()" ajacent to the variable name?

is assigned with the function returned by
of with took the argument of 10.

Question 1. what's the differents when
is assigned to a variable instead of constant? Since here is constant, which part is unchangeable?

Question 2. Why the brackets pair "()" is used with the variable name when calling, I kind of knowing that this might be a function initializer staff. but
is a constant name. Does it equal to the function it points to? Or this is just a general features of a programming language. When you want to use a variable/constant of a function type, you have to use "()" together with the name.

Answer Source

Variable incrementByTen is assigned with the function

This is the key to everything. The value of incrementByTen is a function.

If incrementByTen were a var variable, then it could be reassigned to some other function. Since it's a let variable, it is a constant function. This is exactly identical to var and let variables of type Int. There is no deep difference between integer values and function values. They're just values.

The parentheses mean "call the function." incrementByTen is not the result of calling a function; it is the function itself. It is a value. When that value is evaluated, it returns a function. You can then call that function with the () operator.

This is exactly equivalent to:

makeIncrementer(forIncrement: 10)()

makeIncrementer(forIncrement: 10) returns a function, and () calls that function. This is analogous to:

let x = thingThatReturnsInt()
x + 10

In this case, x is an Int and we can apply the operator + to it. makeIncrementer just happens to return a () -> Int rather than an Int.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download