Structs in Swift

Swift’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This `Person` struct type has `name` and `age` fields.

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

newPerson constructs a new person struct with the given name.

func newPerson(name: String) -> Person {
    var p = Person(name: name, age: 42)
    return p
}

This syntax creates a new struct.

print(Person(name: "Bob", age: 20))

You can name the fields when initializing a struct.

print(Person(name: "Alice", age: 30))

Omitted fields will be zero-valued.

print(Person(name: "Fred", age: 0))

An & prefix yields a pointer to the struct. Note that Swift does not use pointers in the same way as some other languages; instead, you use references and the inout keyword for similar behavior.

print(Person(name: "Ann", age: 40))

It’s idiomatic to encapsulate new struct creation in constructor functions.

print(newPerson(name: "Jon"))

Access struct fields with a dot.

var s = Person(name: "Sean", age: 50)
print(s.name)

Structs are mutable.

s.age = 51
print(s.age)

If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous struct type.

let dog = (name: "Rex", isGood: true)
print(dog)
$ swift main.swift
Person(name: "Bob", age: 20)
Person(name: "Alice", age: 30)
Person(name: "Fred", age: 0)
Person(name: "Ann", age: 40)
Person(name: "Jon", age: 42)
Sean
50
51
(name: "Rex", isGood: true)

Next example: Methods.