Start learning free

LESSON 208 OF 415 · FUNCTIONS & CLASSES

Class Fields in Swift: Stored Properties

Lesson Read the full explanation

TL ; DR:

  • A field is a variable that lives inside a class. Each object of that class has its own copy.


  • Declare a field with a name and a type using var so other code can read and write it:

    class Dog {
        var name: String = ""
        var age: Int = 0
    }
    

  • Access a field on an object with the dot operator: dog.name = "Rex"



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical to every other one. We need a way to attach data to each object.

That's what fields are for. A field is a variable that belongs to a class — and each object created from that class gets its own copy of every field.


Declaring fields

class Dog {
    var name: String = ""
    var age: Int = 0
}
  • var declares a mutable field — any code can read and write it. You'll use let later for fields that should not change after being set.

  • name: String is just a variable declaration — same syntax you'd use anywhere else.


Reading and writing fields

var dog = Dog()
dog.name = "Rex"        // write
dog.age = 4
print(dog.name)   // read → prints "Rex"

Each object has its own slot for every field, so two dogs can have different names without interfering.


Default values

In Swift, every stored property must have a value by the time an object is created, and numbers, Bool and String properties do not get one automatically. Give each a default value in the declaration, or set it in an initializer (a later lesson). Typical defaults are:

  • Numbers: 0

  • Bool: false

  • String: ""

  • An optional property such as var nickname: String? starts as nil without an explicit default


Your task

Update the Dog class to have two fields: name (a String) and age (an Int). Then in mainFunction, set them on the dog object so the pre-filled print prints:

Rex is 4 years old
STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · FUNCTIONS & CLASSES

    Class Fields in Swift, explained

    What a field is

    A field is a variable that belongs to a class, and every object made from the class gets its own copy. Swift's official name for it is a stored property. Without fields, every Dog would be identical; with fields, each one can carry its own name and age.

    Declaring fields

    class Dog {
        var name: String = ""
        var age: Int = 0
    }
    
    • var declares a property that can be read and also assigned a new value. A property declared with let is a constant after it is set.
    • name: String gives the property its type, and = "" gives it a default value.

    Swift requires every stored property to have a value by the time an object exists. A default value satisfies that and also lets you write Dog() with no custom initializer. Without defaults the class doesn't compile:

    class Dog {
        var name: String
        var age: Int
    }
    

    The compiler reports class 'Dog' has no initializers and notes that the properties without an initial value prevent a synthesized initializer. The constructors lesson shows how to write that initializer yourself.

    Defaults are whatever you choose: 0 and "" are common, but there is no automatic zero. For a property that may legitimately have no value, use an optional type: var owner: String? starts as nil with no explicit default.

    Reading and writing fields

    The dot operator reaches a field of one particular object:

    let dog = Dog()
    dog.name = "Rex"
    dog.age = 4
    print("\(dog.name) is \(dog.age) years old")
    

    This prints Rex is 4 years old. Each object has its own slot for each field, so two dogs can hold different names without interfering with one another.

    Notice that dog is declared with let, yet dog.name = "Rex" compiles. For a class, the constant fixes which object dog refers to; the object's var properties can still change. Reassigning the constant itself (dog = Dog()) is an error: cannot assign to value: 'dog' is a 'let' constant. And a property declared with let inside the class can't be assigned from outside either: cannot assign to property: 'species' is a 'let' constant.

    The exercise

    The task has two steps. First, give Dog two var properties with default values, a String called name and an Int called age. Second, set them on the existing dog object before the print line:

    class Dog {
        var name: String = ""
        var age: Int = 0
    }
    
    class Solution {
        func mainFunction() {
            let dog = Dog()
            dog.name = "Rex"
            dog.age = 4
            print("\(dog.name) is \(dog.age) years old")
        }
    }
    

    The output is Rex is 4 years old. The \(...) inside the string literal inserts the value of the expression into the text.

    Common mistakes

    • Omitting default values while also not writing an initializer, which produces the "no initializers" error above.
    • Declaring the fields with let. The assignments dog.name = "Rex" would then be rejected.
    • Setting the fields on the class instead of the object. Dog.name is not valid; fields belong to objects, so use dog.name.
    • Forgetting that objects share through references. If let other = dog, then other.name = "Max" also changes dog.name, because both names point to one object.

    Key takeaways

    • A field, or stored property, is a variable inside a class; each object has its own.
    • Give every stored property a default value, or set it in an initializer.
    • Use the dot operator to read and write: dog.name.
    • A let constant holding a class object still allows its var properties to change.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free