Classes in Swift 101
Image via Author

Classes in Swift 101


In Swift, classes and structs share many similarities, but a few key differences set them apart. Understanding these differences is crucial for choosing the right one for your use case.


Reference Type

A class being a reference type means that class instances are referenced rather than copied when assigned to a variable, passed to a function, or returned from a method. This behaviour contrasts with value types (like structs and enums), which are always copied in similar situations.


Multiple References

Since classes are reference types, assigning a class instance to multiple variables or passing it as an argument to a function creates multiple references to the same object.


Mutability

An instance of a class is mutable. Even if your reference to a class instance is a (let) constant, you can still modify the value of the instance properties you’re referencing.

Note: An instance method of a class cannot be marked as mutating.


Inheritance

A class can inherit its members from another class, with the inherited class referred to as the superclass and the inheriting class called the subclass.

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

Ijeoma Nelson的更多文章

社区洞察