0
0
Swiftprogramming~5 mins

Methods in structs in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a method in a Swift struct?
A method in a Swift struct is a function defined inside the struct that can perform actions using the struct's properties or parameters.
Click to reveal answer
beginner
How do you define a method inside a Swift struct?
You define a method inside a Swift struct by writing a function inside the struct's curly braces, like this:<br>
struct Example {<br>  func greet() {<br>    print("Hello")<br>  }<br>}
Click to reveal answer
intermediate
What keyword do you use to modify properties inside a method of a struct?
You use the mutating keyword before the method to allow it to change properties of the struct.
Click to reveal answer
intermediate
Why do methods in structs sometimes need the 'mutating' keyword?
Because structs are value types, methods that change their properties must be marked with 'mutating' to tell Swift the method will modify the struct itself.
Click to reveal answer
beginner
Can methods in structs return values? Give an example.
Yes, methods in structs can return values.<br>Example:<br>
struct Circle {<br>  var radius: Double<br>  func area() -> Double {<br>    return 3.14 * radius * radius<br>  }<br>}
Click to reveal answer
What keyword must you add to a struct method that changes its properties?
Amutating
Bchanging
Cvar
Dmodifying
Where do you define methods in a Swift struct?
AInside the struct's curly braces
BOutside the struct
COnly in classes, not structs
DIn a separate file
Can a method in a struct return a value?
AOnly if marked mutating
BNo, methods cannot return values
COnly if the struct is a class
DYes, methods can return values
Why do some struct methods need the 'mutating' keyword?
ABecause it makes the method faster
BBecause structs are value types and need explicit permission to change
CBecause classes require it
DBecause methods always need 'mutating'
Which of these is a valid method inside a struct?
Avar greet = "Hi"
Bclass greet() {}
Cfunc greet() { print("Hi") }
Dlet greet = func() {}
Explain how to create and use a method inside a Swift struct.
Think about how you write a function inside the struct and then use it.
You got /3 concepts.
    Describe why the 'mutating' keyword is important for methods in structs.
    Consider how structs behave differently from classes.
    You got /3 concepts.