0
0
Swiftprogramming~10 mins

Functions as types 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 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'
Afunc(Int, Int) -> Int
BInt -> Int
CInt, Int -> Int
D(Int, Int) -> Int
Attempts:
3 left
💡 Hint
Common Mistakes
Writing function types without parentheses around input parameters.
Using 'func' keyword inside the type declaration.
2fill in blank
medium

Complete 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'
Aadd(a:b:)
Badd
Cadd()
Dadd(a, b)
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the function with parentheses instead of referencing it.
Omitting parameter labels in the function reference.
3fill in blank
hard

Fix 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'
AString -> Bool
B(String) -> Bool
C(String, Bool)
Dfunc(String) -> Bool
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting parentheses around input types.
Including 'func' keyword in the type.
4fill in blank
hard

Fill 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'
AString
B(Int) -> String
CInt
DString -> Int
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping key and value types.
Using incorrect function type syntax.
5fill in blank
hard

Fill 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'
A(Int, Int) -> Int
BInt
D()->Void
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent types for function parameter and closure.
Wrong return type for performOperation.