I'm reading the iBook The Swift Programming Language and seeing a convention that I don't understand and hasn't been explained in the book: variable and functions followed by a single line with the variable or function name by itself.
For example:
var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
do {
m = m * 2
} while m < 100
m
And:
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
What is the purpose of these lines where the variable or function name are on a line by themselves?
TIA
Swift – Assign Function to a Variable To assign function to a variable in Swift, declare a variable that takes specific set/type of parameters and return a specific type of value. Then we can assign a function that has same type of parameters and return value to this variable.
Swift employs the keywords let and var for naming variables. The let keyword declares a constant, meaning that it cannot be re-assigned after it's been created (though its variable properties can be altered later). The var keyword declares a new variable, meaning that the value it holds can be changed at a later time.
Every function in Swift has a type, consisting of the function's parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions.
A function is a set of statements organized together to perform a specific task. A Swift 4 function can be as simple as a simple C function to as complex as an Objective C language function. It allows us to pass local and global parameter values inside the function calls.
The purpose is for "Playground" Demonstrations. For example, if you put that code into playground. The window on the right will show result of the execution of the function.
If you were in a traditional project, you would likely do:
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
var someInt = returnFifteen()
println(someInt)
However, this is unnecessary in Playground:
Notice the right side.
When you are using Swift in the playground, the output display on the right hand side is not actually a console output more so just an output of whatever variable is on that line, or the number of times a loop runs.
So they are placing the variable/function on it's own line so that when you paste that into Playground you will see what the result is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With