Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a method named greet inside the struct.
Swift
struct Person {
var name: String
func [1]() {
print("Hello, \(name)!")
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from 'greet' will cause the method not to be recognized.
✗ Incorrect
The method name should be greet as defined in the instruction.
2fill in blank
mediumComplete the code to call the greet method on the person instance.
Swift
var person = Person(name: "Anna") person.[1]()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method name that does not exist on the struct instance.
✗ Incorrect
To call the method defined as greet, use person.greet().
3fill in blank
hardFix the error by completing the method signature to modify the struct's property.
Swift
struct Counter {
var count = 0
mutating func [1]() {
count += 1
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not match the intended action.
✗ Incorrect
The method name increment clearly indicates increasing the count by one.
4fill in blank
hardFill both blanks to create a method that returns a greeting with the person's name.
Swift
struct Person {
var name: String
func [1]() -> String {
return "Hello, \([2])!"
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a property name that does not exist in the struct.
✗ Incorrect
The method is named greet and it returns a string using the property name.
5fill in blank
hardFill all three blanks to define a mutating method that resets the count to zero and returns a message.
Swift
struct Counter {
var count: Int
mutating func [1]() -> String {
count = [2]
return "Count reset to [3]"
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-mutating method to change a property.
✗ Incorrect
The method named reset sets count to 0 and returns a message with the word 'zero'.