0
0
Swiftprogramming~10 mins

Methods in structs 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 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'
Agreeting
BsayHello
Chello
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from 'greet' will cause the method not to be recognized.
2fill in blank
medium

Complete 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'
Agreet
BsayHello
Chello
Dgreeting
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a method name that does not exist on the struct instance.
3fill in blank
hard

Fix 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'
Aincrement
Bincrease
CaddOne
Dmutate
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not match the intended action.
4fill in blank
hard

Fill 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'
Agreet
Bname
CpersonName
DsayHello
Attempts:
3 left
💡 Hint
Common Mistakes
Using a property name that does not exist in the struct.
5fill in blank
hard

Fill 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'
Areset
B0
Czero
Dclear
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-mutating method to change a property.