0
0
Swiftprogramming~10 mins

Autoclosures (@autoclosure) 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 parameter as an autoclosure.

Swift
func logIfTrue(_ predicate: [1]) {
    if predicate() {
        print("Condition is true")
    }
}
Drag options to blanks, or click blank then click option'
A() -> Bool
BBool
C@escaping () -> Bool
D@autoclosure () -> Bool
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add '@autoclosure' before the closure type.
Using just 'Bool' instead of a closure type.
Using '@escaping' which is not needed here.
2fill in blank
medium

Complete the code to call the function with an autoclosure parameter.

Swift
logIfTrue([1] > 5)
Drag options to blanks, or click blank then click option'
A3 + 4
B3 > 4
C7
Dtrue
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a Boolean literal directly without an expression.
Passing a value that is not a Boolean expression.
3fill in blank
hard

Fix the error in the function declaration to correctly use @autoclosure.

Swift
func check(_ condition: [1]) {
    if condition() {
        print("Checked true")
    }
}
Drag options to blanks, or click blank then click option'
A@autoclosure () -> Bool
BBool
C() -> Bool
D@escaping () -> Bool
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Bool' instead of a closure type.
Using '@escaping' which is not needed here.
4fill in blank
hard

Fill both blanks to declare a function with an autoclosure parameter and call it correctly.

Swift
func evaluate(_ expression: [1]) {
    print("Result is \(expression())")
}
evaluate([2])
Drag options to blanks, or click blank then click option'
A@autoclosure () -> Int
B5 * 3
C5 + 3
DInt
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Int' instead of a closure type for the parameter.
Passing a value without an expression.
5fill in blank
hard

Fill all three blanks to create a function with an autoclosure and escaping parameter, then call it.

Swift
func storeCondition(_ condition: [1], completion: @escaping () -> Void) {
    if condition() {
        completion()
    }
}

let conditionClosure: [2] = [3] > 10
Drag options to blanks, or click blank then click option'
A@autoclosure () -> Bool
B() -> Bool
C15
D20
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Bool' instead of closure types.
Assigning a raw value instead of an expression to the closure variable.