Swift Functions and Optionals Flashcards

1
Q

What is a function?

How is function exectuted?

A

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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Syntax and Parameters of Functions?

How to add Paramenters?

Are there any rules for naming a function?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are “Named Parameters”?

How to create it??

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are Tuples?

How do use it?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a boolean value?

A

Boolean value either take true or false e.g.

var found = false
for name in names {
if name == names{

found = true
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Decomposing a Tuple:

A

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 )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly