What Is a Struct?
Bundle related values into one, then build one.
1struct Dog {
2 var name: String
3}
4
5let rex = Dog(name: "Rex")
6print(rex.name)
$ swift main.swift
Rex
Every line, explained
struct Dog {- struct Dog { ... } defines a struct: a blueprint bundling values that belong together. Swift developers reach for structs first when they want to model a "thing". Struct names start with a capital letter by convention.
var name: String- A variable inside a struct is called a property; every Dog gets its own. Every Dog has a name, and it is a String.
}- This } closes the struct.
let rex = Dog(name: "Rex")- Swift writes the builder for you! Because Dog lists its properties, Swift automatically lets you build one with labels: Dog(name: "Rex"). (Other languages make you write this "constructor" yourself.) rex now holds one actual dog, name already filled in.
print(rex.name)- print(...) works exactly as in Intro to Swift. The dot reads a property: rex.name is the name stored on rex.