0
0
Swiftprogramming~10 mins

Actor isolation concept 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 an actor named Counter.

Swift
actor [1] {
    var value = 0
}
Drag options to blanks, or click blank then click option'
ACounter
Bclass
Cstruct
Denum
Attempts:
3 left
💡 Hint
Common Mistakes
Using class, struct, or enum instead of actor.
2fill in blank
medium

Complete the code to define an isolated method increment() inside the actor.

Swift
actor Counter {
    var value = 0
    func [1]() {
        value += 1
    }
}
Drag options to blanks, or click blank then click option'
Adecrement
Bincrement
Creset
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names that do not match the action, like decrement or reset.
3fill in blank
hard

Fix the error by completing the code to call the isolated method increment() from outside the actor.

Swift
let counter = Counter()
Task {
    await counter.[1]()
}
Drag options to blanks, or click blank then click option'
Areset
Bvalue
Cinit
Dincrement
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access the property directly without await.
Using wrong method names.
4fill in blank
hard

Fill both blanks to define an isolated computed property and access it asynchronously.

Swift
actor Counter {
    var value = 0
    var [1]: Int {
        return value
    }
}

let counter = Counter()
Task {
    let currentValue = await counter.[2]
}
Drag options to blanks, or click blank then click option'
AcurrentValue
Bvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the property and access.
Not using await when accessing the property.
5fill in blank
hard

Fill all three blanks to define an actor with an isolated method, call it asynchronously, and print the result.

Swift
actor Counter {
    var value = 0
    func [1]() {
        value += 1
    }
}

let counter = Counter()
Task {
    await counter.[2]()
    print(counter.[3])
}
Drag options to blanks, or click blank then click option'
Aincrement
Cvalue
DcurrentValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method or property names.
Not using await when calling the method.