Meet the Class
Swift has classes too; spot the difference.
1class Puppy {
2 var name = "Buddy"
3}
4
5let buddy = Puppy()
6buddy.name = "Max"
7print(buddy.name)
$ swift main.swift
Max
Every line, explained
class Puppy {- class defines a blueprint too, and looks almost identical to a struct. The difference is in how values are handled: every struct value is its own independent copy, while a class object can be SHARED: several variables can point at the same one.
var name = "Buddy"- A property with a starting value, so building a Puppy needs no labels.
}- This } closes the class.
let buddy = Puppy()- Builds one Puppy object.
buddy.name = "Max"- Wait: buddy is a let, and we just changed it?! With a class, let only locks WHICH object buddy points at; the object's own properties can still change. A struct would have refused. This is the big struct/class difference in action.
print(buddy.name)- print(...) works exactly as in Intro to Swift. Rule of thumb in Swift: use structs by default, and classes when you need sharing.