Swift Functions and Optionals Flashcards
What is a function?
How is function exectuted?
Code to excute any function, written as
func name () { // in () would be parameter let height = 12 let width = 10 let area = height \* width println("The area of the room is \(area)")
}
executed by adding new line nameoffunc()
What is Syntax and Parameters of Functions?
How to add Paramenters?
Are there any rules for naming a function?
func calculateArea() {}
In () are Parameters of function
Adding Parameters:
func calculateArea(heigh: Int, width: Int) { let area = height \* width println("The area of the room is \(area)")
}
Now when executing function, it asks me to fill in parameters
Name a function= Must start with letter, not number or character
What are “Named Parameters”?
How to create it??
Can add labels to parameters e.g.
calculateArea(height:100 , width: 200 , units:”meters” )
height: Parameter Label; 100 Parameter Value (almost like dictionary with key value pairs)
TO CREATE
Initial Parameters (height: Int, width: Int)
Changed Parameters (height height: Int, width width: Int)
or (#height: Int, #width: Int) //because label and parameter name are same
What are Tuples?
How do use it?
Used in functions to return multiple values (Return function only returns one)
Example:
var found = (false, “(Name) is not found”) // First part boolean, second string
than, if the variable found is used later for example in if function, it needs to apply same structure: found = (true, “(name) is found”)
Also adjustment in definition of return function, after parameters -> needs to be done e.g. -> (Bool, String) // before it was -> Bool
What is a boolean value?
Boolean value either take true or false e.g.
var found = false for name in names { if name == names{
found = true
}
}
Decomposing a Tuple:
Means accessing individiual items
Example:
let (found, description) = searchNames(name: “Jon”)
// searchNames name of func; through first bracelts we assign to tuple and assign names to elements
If only interested in only one score let (_,description )