0
0
iOS Swiftmobile~10 mins

Functions and closures in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a simple function that prints a greeting.

iOS Swift
func greet() {
  print([1])
}
Drag options to blanks, or click blank then click option'
A"Hello, world!"
BHello, world!
Cprint("Hello")
Dgreet()
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the double quotes around the string.
Trying to call print inside print.
2fill in blank
medium

Complete the code to declare a closure that adds two integers.

iOS Swift
let add: (Int, Int) -> Int = [1]
Drag options to blanks, or click blank then click option'
A{ a, b in a - b }
B(a, b) -> a + b
Cfunc(a, b) { a + b }
D{ (a: Int, b: Int) in return a + b }
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect closure syntax without 'in'.
Using subtraction instead of addition.
3fill in blank
hard

Fix the error in the function that returns a closure capturing a variable.

iOS Swift
func makeIncrementer() -> () -> Int {
  var count = 0
  return [1] {
    count += 1
    return count
  }
}
Drag options to blanks, or click blank then click option'
Aclosure()
Bfunc()
C{
D-> Int in
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'func()' instead of '{' to start the closure.
Adding extra keywords inside the return statement.
4fill in blank
hard

Fill both blanks to create a closure that filters even numbers from an array.

iOS Swift
let numbers = [1, 2, 3, 4, 5]
let evens = numbers.filter { [1] in [2] % 2 == 0 }
Drag options to blanks, or click blank then click option'
Anumber
Bnum
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names before 'in' and inside the closure.
Using undefined variable names.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension filtering values greater than zero.

iOS Swift
let data = ["a": 1, "b": -1, "c": 3]
let filtered = data.filter { [1], [2] in [3] > 0 }
Drag options to blanks, or click blank then click option'
Akey
Bvalue
Cval
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent parameter names.
Checking the key instead of the value.