📜  struct exsmple - Swift (1)

📅  最后修改于: 2023-12-03 15:20:21.986000             🧑  作者: Mango

Struct Example - Swift

In Swift, a struct is a data structure that stores related values. They are similar to classes, but with some important differences.

Declaration

To declare a struct, use the struct keyword followed by the name of the struct. Here's an example:

struct Person {
    var name: String
    var age: Int
}

This defines a Person struct with two properties: name and age.

Initialization

To create a new instance of a struct, you can use the initializer syntax.

let person = Person(name: "John", age: 30)

This creates a new Person instance with the name "John" and age 30.

Value Types

One key difference between structs and classes is that structs are value types. This means that when you assign a struct to a variable or pass it to a function, a copy of the struct is created.

var person1 = Person(name: "John", age: 30)
var person2 = person1

person1.age = 31

print(person1.age) // 31
print(person2.age) // 30

In this example, we create two instances of Person. When we assign person1 to person2, a copy of the struct is created, so they are independent of each other. When we update the age property of person1, it doesn't affect person2.

Mutating Functions

If you want to modify a struct's properties, you need to mark the function as mutating.

struct Counter {
    var count = 0
    
    mutating func increment() {
        count += 1
    }
}

var counter = Counter()
counter.increment()
print(counter.count) // 1

In this example, we define a Counter struct with a single property: count. We also define a mutating function increment that adds 1 to the count. When we create a new instance of Counter and call the increment function, the count is updated to 1.

Structs can be a powerful tool for organizing and manipulating data in your Swift code. By understanding how they work, you can take advantage of their unique features to write cleaner and more efficient code.