0
0
Swiftprogramming~10 mins

Classes are reference types 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 new instance of the class.

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

let myDog = [1](name: "Buddy")
Drag options to blanks, or click blank then click option'
ADog()
BDog
Cdog
Dclass Dog
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'dog' instead of 'Dog'.
Adding parentheses after the class name when not needed.
2fill in blank
medium

Complete the code to change the name property of the Dog instance.

Swift
let myDog = Dog(name: "Buddy")
myDog.[1] = "Max"
Drag options to blanks, or click blank then click option'
Aname
BName()
CsetName
DName
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase 'Name' instead of lowercase 'name'.
Trying to call a method 'setName' which does not exist.
3fill in blank
hard

Fix the error in the code to make both variables refer to the same Dog instance.

Swift
let dog1 = Dog(name: "Buddy")
let dog2 = [1]
dog2.name = "Charlie"
print(dog1.name)
Drag options to blanks, or click blank then click option'
Adog1
BDog(name: "Charlie")
CDog()
Ddog2
Attempts:
3 left
💡 Hint
Common Mistakes
Creating a new Dog instance instead of assigning dog1.
Assigning dog2 to itself before initialization.
4fill in blank
hard

Fill both blanks to complete the class method that changes the dog's name.

Swift
class Dog {
    var name: String
    init(name: String) {
        self.name = name
    }
    func [1](newName: String) {
        self.[2] = newName
    }
}
Drag options to blanks, or click blank then click option'
AchangeName
Bname
CupdateName
DnewName
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'newName' as the property name instead of 'name'.
Using a method name that is not descriptive.
5fill in blank
hard

Fill all three blanks to create a copy of a Dog instance and change the copy's name without affecting the original.

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

let dog1 = Dog(name: "Buddy")
let dog2 = dog1.[2]()
dog2.[3] = "Max"
print(dog1.name)
Drag options to blanks, or click blank then click option'
Aname
Bcopy
DchangeName
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning dog2 = dog1 instead of copying.
Changing dog2's name property incorrectly.