0
0
Swiftprogramming~10 mins

Closure expression syntax in 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 create a closure that adds two numbers.

Swift
let add = { (a: Int, b: Int) -> Int in return a [1] b }
Drag options to blanks, or click blank then click option'
A/
B-
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' will subtract instead of add.
2fill in blank
medium

Complete the code to call the closure with arguments 3 and 5.

Swift
let result = add([1], 5)
Drag options to blanks, or click blank then click option'
A4
B3
C5
D6
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 4 or 6 instead of 3 will change the result.
3fill in blank
hard

Fix the error in the closure syntax to correctly multiply two numbers.

Swift
let multiply = { (a: Int, b: Int) -> Int [1] a * b }
Drag options to blanks, or click blank then click option'
Afunc
B->
Cin
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' or 'func' instead of 'in' causes syntax errors.
4fill in blank
hard

Fill both blanks to create a closure that returns the square of a number.

Swift
let square = { (num: Int) [1] num [2] num }
Drag options to blanks, or click blank then click option'
Ain
B**
C*
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using '**' for exponentiation is not valid in Swift.
5fill in blank
hard

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

Swift
let evens = numbers.filter { [1] in [2] % 2 [3] 0 }
Drag options to blanks, or click blank then click option'
Anum
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '==' will filter odd numbers instead.