More Properties
Give the struct several properties.
1struct Dog {
2 var name: String
3 var age: Int
4}
5
6let rex = Dog(name: "Rex", age: 3)
7print("\(rex.name) is \(rex.age)")
$ swift main.swift
Rex is 3
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".
var name: String- A variable inside a struct is called a property; every Dog gets its own.
var age: Int- A struct can bundle as many properties as you need, of any types. Every Dog now has a name AND an age.
}- This } closes the struct.
let rex = Dog(name: "Rex", age: 3)- 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.) With two properties, the automatic builder takes two labelled values.
print("\(rex.name) is \(rex.age)")- print(...) works exactly as in Intro to Swift. String interpolation works on properties too.