0
0
Swiftprogramming~5 mins

Struct declaration syntax in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a struct in Swift?
A struct is a way to group related data and functions together. It is a custom data type that can hold properties and methods.
Click to reveal answer
beginner
How do you declare a simple struct named Person with a name property of type String?
You write:<br>
struct Person {
    var name: String
}
Click to reveal answer
intermediate
Can structs in Swift have functions inside them? How?
Yes, structs can have functions called methods. You define them inside the struct like this:<br>
struct Person {
    var name: String
    func greet() {
        print("Hello, \(name)!")
    }
}
Click to reveal answer
beginner
What keyword do you use to create a new instance of a struct?
You use the struct's name followed by parentheses with any required parameters. For example:<br><pre>let person = Person(name: "Alice")</pre>
Click to reveal answer
intermediate
Are structs in Swift value types or reference types? What does that mean?
Structs are value types. This means when you assign or pass a struct, you get a copy, not a reference to the original. Changes to the copy do not affect the original.
Click to reveal answer
Which keyword is used to declare a struct in Swift?
Astruct
Bclass
Cenum
Dtype
How do you define a property inside a struct?
Avar propertyName: Type
BpropertyName = Type
Clet propertyName Type
Ddef propertyName: Type
What happens when you assign one struct instance to another variable?
AThe original struct is deleted
BBoth variables point to the same instance
CAn error occurs
DA copy of the struct is created
Which of these can a Swift struct contain?
AOnly properties
BProperties and methods
COnly methods
DNeither properties nor methods
How do you create a new instance of a struct named Car with a property model?
Avar car = Car.model("Tesla")
Blet car = new Car("Tesla")
Clet car = Car(model: "Tesla")
DCar car = Car("Tesla")
Explain how to declare a struct in Swift and include a property and a method.
Think about grouping data and behavior inside one block.
You got /4 concepts.
    Describe the difference between structs and classes in Swift regarding value and reference types.
    Focus on how data is copied or shared.
    You got /4 concepts.