0
0
Swiftprogramming~5 mins

Nested functions in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a nested function in Swift?
A nested function is a function defined inside another function. It can only be used within the outer function where it is declared.
Click to reveal answer
beginner
Why use nested functions in Swift?
Nested functions help organize code by grouping related tasks together. They also can access variables from the outer function, making code cleaner and easier to read.
Click to reveal answer
intermediate
Can a nested function access variables from its outer function in Swift?
Yes, a nested function can use and modify variables declared in its outer function because it shares the same scope.
Click to reveal answer
beginner
Example of a nested function in Swift:
func greet() { func sayHello() { print("Hello!") } sayHello() } Here, sayHello() is nested inside greet() and can only be called within greet().
Click to reveal answer
intermediate
What happens if you try to call a nested function from outside its outer function in Swift?
You get a compile-time error because nested functions are not visible outside their outer function's scope.
Click to reveal answer
Where can a nested function be called in Swift?
AOnly inside its outer function
BAnywhere in the program
COnly inside other nested functions
DOnly in the main program
Can a nested function access variables declared in its outer function?
AYes, it shares the same scope
BNo, it has its own separate scope
COnly if variables are global
DOnly if variables are constants
What is a benefit of using nested functions?
AThey can be called from anywhere
BThey run faster than normal functions
CThey help organize code and limit scope
DThey automatically make code asynchronous
What error occurs if you call a nested function outside its outer function?
ARuntime error
BLogical error
CNo error, it works fine
DCompile-time error
Which keyword is used to define a nested function in Swift?
Anested
Bfunc
Cinner
Ddef
Explain what nested functions are and why you might use them in Swift.
Think about how functions inside functions help keep code tidy and safe.
You got /4 concepts.
    Describe how variable scope works with nested functions in Swift.
    Consider where variables live and who can see them.
    You got /3 concepts.