Instance vs Static Properties Explained in Swift

Instance vs Static Properties Explained in Swift

In Swift, a property is a variable or constant declared at the top level of an object such as a class, structure or enumeration.

A property is only visible through the object. If the object has a method then the method can see and access the property either by using the dot notation with the self keyword or omitting the self altogether except in situations of ambiguity.


class User {
    
    let name = "Ijeoma"
    
    func printUserName() {
        print(self.name)
    }
}

let myUser = User()

myUser.printUserName()

// Ijeoma        

Here, the User class has a property named name and a function named printUserName that accesses the property through the dot notation using the self keyword.

The class is instantiated and the instance is assigned to the constant myUser. The dot notation is used to refer to printUserName() which prints the value, “Ijeoma.”

The property in this example is an instance property.

When properties store values associated with instances of a type, they are known as instance properties; and when they store values for the type itself, they are known as static properties.



Instance Properties

By default, an instance property is also visible to other code with access to its object. In such cases, the instance property can be accessed through the dot notation using the instance name (rather than self) as the reference.


class User {
    
    let name = "Ijeoma"
    
    func printUserName() {
        print(self.name)
    }
}

class Greet {
    
    func greetUser() {
        print("Hello, \(User().name)")
    }
}

let greeting = Greet()

greeting.greetUser()

// Hello, Ijeoma
        

The greetUser() method of the Greet{...} object is accessing the name property of the User{...} object through the dot notation using the name of the object.

Greet{...} is initialized and assigned to the constant greeting. The dot notation is used to access the method greetUser().


Note: The values for instance properties can differ for each instance declared and its lifetime is determined by the lifetime of the instance. When an object is instantiated, its instance comes into existence and remains active as long as the variable or constant it is assigned to is being used by the program.


Static Properties


class User {
    
    static let name = "Ijeoma"
}

print(User.name)


// Ijeoma        

To declare a static property you use the keyword static and to access it you use the class name with the dot notation. There’s no need to instantiate the object because a static property is not associated with any instances, rather, it belongs to the object. This is the reason it’s also referred to as a type property.

The lifetime of a static property depends on the lifetime of the object. For example, if the object is declared at the top level of a file, then the object is active for the entire duration of the program and so is the static property.


Note: By default, static properties can be seen by any code that has access to its object and in such cases they can be referenced through the dot notation using the object name.


Instance vs Static Property

Instance properties are indeed more common but that doesn’t mean that static properties have no value.

A general rule I follow is to make the property an instance property if the object needs to be instantiated, otherwise, it’s static.

要查看或添加评论,请登录

Ijeoma Nelson的更多文章

  • Swift Object Features

    Swift Object Features

    In “Everything is an Object,” I discuss Swift’s approach to the concept of objects. If you’re unfamiliar with Swift…

  • Classes and Structures in Swift

    Classes and Structures in Swift

    In Swift, structures and classes are two powerful building blocks for organising code. Each one provides a way to store…

  • Swift Optionals: Here’s What You Need to Know

    Swift Optionals: Here’s What You Need to Know

    Lessons in avoiding unexpected app crashes! Ensuring data is ready and available when users request it is crucial to…

  • Comparison with Optional Values in Swift

    Comparison with Optional Values in Swift

    How it works..

  • How to transform an Optional Value in Swift

    How to transform an Optional Value in Swift

    In my last article, I explained that to send a message to a value wrapped in an Optional you must first unwrap the…

  • Optional Chaining Explained in Swift

    Optional Chaining Explained in Swift

    The proper way to send a message to an Optional! This article assumes you know what a Swift Optional is and how to…

  • An Introduction to Swift Optional and the Keyword nil

    An Introduction to Swift Optional and the Keyword nil

    This is a lesson in how to safely unwrap an Optional! This article assumes prior knowledge of the Swift Optional. If…

  • How to Use an Implicitly Unwrapped Optional in Swift

    How to Use an Implicitly Unwrapped Optional in Swift

    This article assumes you understand what Optionals are in Swift. If this is not the case, I recommend you read Swift…

  • Swift Optional Explained

    Swift Optional Explained

    Maybe it contains a value, maybe it doesn’t! In Swift, an Optional is a type of enumeration that represents a wrapped…

  • Swift Tuple Explained

    Swift Tuple Explained

    Think of a Tuple as a bespoke collection of values. To define a Tuple, you wrap the comma-separated selection of values…

    1 条评论

社区洞察

其他会员也浏览了