Complete the code to create a class instance and assign it to a variable.
class Person { var name: String init(name: String) { self.name = name } } let person1 = [1](name: "Alice")
We create an instance of the Person class by calling Person(name: "Alice").
Complete the code to assign one class instance to another variable, sharing the reference.
let person2 = person1 person2.name = "Bob" print(person1.name) // Output: [1]
Both person1 and person2 refer to the same instance, so changing person2.name changes person1.name.
Fix the error in the code to prevent side effects by copying the instance.
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"
self instead of a new instance.copy() recursively inside itself.The copy() method creates a new Person instance with the same name, avoiding shared references.
Fill in the blank to populate the dictionary with names only if they start with 'A'.
let names = ["Alice", "Bob", "Anna", "Charlie"] var filteredNames = [String: String]() for name in names { if name.[1]("A") { filteredNames[name] = name } } print(filteredNames)
startsWith.contains which checks anywhere in the string.In Swift, hasPrefix("A") checks if a string starts with "A".
Fill all three blanks to create a dictionary of name lengths for names longer than 3 characters.
let names = ["Eve", "Alice", "Bob", "Charlie"] var nameLengths = [String: Int]() for [3] in names { if [2] > 3 { nameLengths[[1]] = [2] } } print(nameLengths)
length.The loop uses name as the loop variable and key, name.count as the condition and value.