Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a function type variable that takes two Ints and returns an Int.
Swift
var operation: [1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Writing function types without parentheses around input parameters.
Using 'func' keyword inside the type declaration.
✗ Incorrect
In Swift, a function type is written as (InputTypes) -> ReturnType. Here, the function takes two Ints and returns an Int, so the correct type is (Int, Int) -> Int.
2fill in blank
mediumComplete the code to assign a function that adds two Ints to the variable 'operation'.
Swift
func add(a: Int, b: Int) -> Int {
return a + b
}
var operation: (Int, Int) -> Int = [1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the function with parentheses instead of referencing it.
Omitting parameter labels in the function reference.
✗ Incorrect
In Swift, to assign a function to a variable, you use the function's name with its parameter labels and colon, like 'add(a:b:)'.
3fill in blank
hardFix the error in the function type declaration that should accept a String and return a Bool.
Swift
var check: [1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting parentheses around input types.
Including 'func' keyword in the type.
✗ Incorrect
The correct function type syntax uses parentheses around input types and an arrow to the return type, like (String) -> Bool.
4fill in blank
hardFill both blanks to create a dictionary that maps String keys to functions taking Int and returning String.
Swift
var handlers: [[1]: [2]] = [:]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping key and value types.
Using incorrect function type syntax.
✗ Incorrect
The dictionary keys are Strings, and the values are functions with type (Int) -> String.
5fill in blank
hardFill all three blanks to define a function that takes a function as parameter and returns an Int.
Swift
func performOperation(_ op: [1]) -> [2] { return op(5, 3) } let add: [3] = { $0 + $1 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent types for function parameter and closure.
Wrong return type for performOperation.
✗ Incorrect
The function parameter 'op' is a function type (Int, Int) -> Int, the return type is Int, and 'add' is a closure of type (Int, Int) -> Int.