0
0
Swiftprogramming~10 mins

Reference sharing and side effects 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 create a class instance and assign it to a variable.

Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

let person1 = [1](name: "Alice")
Drag options to blanks, or click blank then click option'
AString
BArray
CInt
DPerson
Attempts:
3 left
💡 Hint
Common Mistakes
Using a type like String or Int instead of the class name.
Forgetting to call the initializer with parentheses.
2fill in blank
medium

Complete the code to assign one class instance to another variable, sharing the reference.

Swift
let person2 = person1
person2.name = "Bob"
print(person1.name)  // Output: [1]
Drag options to blanks, or click blank then click option'
A"Unknown"
B"Bob"
C"Charlie"
D"Alice"
Attempts:
3 left
💡 Hint
Common Mistakes
Thinking that assigning creates a copy of the instance.
Expecting the original name to stay "Alice".
3fill in blank
hard

Fix the error in the code to prevent side effects by copying the instance.

Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
    func copy() -> Person {
        return [1](name: self.name)
    }
}

let person1 = Person(name: "Alice")
let person2 = person1.copy()
person2.name = "Bob"
print(person1.name)  // Output: "Alice"
Drag options to blanks, or click blank then click option'
APerson
Bself
Ccopy
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Returning self instead of a new instance.
Calling copy() recursively inside itself.
4fill in blank
hard

Fill in the blank to populate the dictionary with names only if they start with 'A'.

Swift
let names = ["Alice", "Bob", "Anna", "Charlie"]
var filteredNames = [String: String]()
for name in names {
  if name.[1]("A") {
    filteredNames[name] = name
  }
}
print(filteredNames)
Drag options to blanks, or click blank then click option'
Acontains
BstartsWith
ChasPrefix
DendsWith
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like startsWith.
Using contains which checks anywhere in the string.
5fill in blank
hard

Fill all three blanks to create a dictionary of name lengths for names longer than 3 characters.

Swift
let names = ["Eve", "Alice", "Bob", "Charlie"]
var nameLengths = [String: Int]()
for [3] in names {
  if [2] > 3 {
    nameLengths[[1]] = [2]
  }
}
print(nameLengths)
Drag options to blanks, or click blank then click option'
Aname
Bname.count
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined variables like length.
Mixing up keys and values in the dictionary.