0
0
Swiftprogramming~10 mins

ARC overview for memory management 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 strong reference to an instance.

Swift
var person: Person? = [1] Person()
Drag options to blanks, or click blank then click option'
Aunowned
Bweak
Cstrong
Dlazy
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'weak' or 'unowned' when declaring a variable without initialization.
2fill in blank
medium

Complete the code to declare a weak reference to avoid retain cycles.

Swift
class Person {
    weak var friend: [1]?
}
Drag options to blanks, or click blank then click option'
APerson
BString
CInt
DBool
Attempts:
3 left
💡 Hint
Common Mistakes
Using value types like String or Int with 'weak'.
3fill in blank
hard

Fix the error in the code to prevent a strong reference cycle.

Swift
class Customer {
    var card: [1]?
}

class CreditCard {
    var owner: Customer?
}
Drag options to blanks, or click blank then click option'
ACreditCard
Bunowned CreditCard
Cweak CreditCard
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using strong references causing retain cycles.
Using 'weak' when the reference should not be optional.
4fill in blank
hard

Fill both blanks to create a dictionary with keys as names and values as their lengths, filtering names longer than 3 characters.

Swift
let names = ["Anna", "Bob", "Catherine", "Dave"]
let nameLengths = [[1]: [2] for name in names if name.count > 3]
Drag options to blanks, or click blank then click option'
Aname
Bname.count
Cname.length
Dlen(name)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'name.length' which is not valid in Swift.
Using 'len(name)' which is Python syntax.
5fill in blank
hard

Fill all three blanks to create a closure that captures self weakly and prints a message.

Swift
class Printer {
    func printMessage() {
        let closure = { [[1] self] in
            print("Message from [2]")
        }
        closure()
    }
}

let printer = Printer()
printer.printMessage()
Drag options to blanks, or click blank then click option'
Aweak
Bstrong
Cself
DPrinter
Attempts:
3 left
💡 Hint
Common Mistakes
Not capturing self weakly causing retain cycles.
Using 'strong' which is not a capture keyword.