Swift 101: Classes, Variables, Properties, and Methods
In Swift, classes define reference-type objects, variables hold values, properties store or expose data, and methods are functions attached to a type or instance. These ideas fit together: you declare a class, give it properties to represent its state, and add methods to describe what it can do.
How Swift Organizes These Concepts
Swift is a strongly typed programming language, so each stored value has a type, such as Int, String, or a custom class. A class is a blueprint for making instances; each instance can have its own data and behavior.
For example, a program for tracking a book might define a Book class. A book instance could store its title and page count, while a method could mark it as read. The class describes the shared structure and behavior, but each instance has its own property values.
Not every Swift type is a class. Structs and enums are also common ways to define custom types, and choosing among them matters because classes have reference semantics while structs and enums have value semantics.
Variables and Constants
A variable is a named place to hold a value. Swift uses var to declare a variable whose value may change, and let to declare a constant that cannot be reassigned after initialization.
var pageCount = 320
let title = "A Swift Guide"
pageCount = 325
// title = "Another Title" // Error: a let constant cannot be reassigned
Swift can often infer a type from the initial value, as it infers Int for pageCount and String for title. You can also write the type explicitly:
var pageCount: Int = 320
A key distinction: let means the binding cannot be reassigned; it does not make every object reachable through that binding deeply immutable. For a class instance stored in a let constant, the constant cannot point to a different instance, but the instance’s mutable properties may still change.
Properties: Data Belonging to a Type
Properties are values associated with a type or one of its instances. A stored property keeps a value directly. In a class, each instance normally has its own stored instance properties.
class Book {
var title: String
var pageCount: Int
init(title: String, pageCount: Int) {
self.title = title
self.pageCount = pageCount
}
}
The init method is an initializer: it prepares a new instance and assigns initial values to its stored properties. Swift requires non-optional stored properties to have values before initialization finishes. Here, self.title means the instance’s property, while title on the right is the initializer parameter.
Swift also supports computed properties. Instead of storing a separate value, a computed property calculates its result when accessed:
class Book {
var pageCount: Int
var isLong: Bool {
pageCount >= 500
}
init(pageCount: Int) {
self.pageCount = pageCount
}
}
Properties can have observers such as willSet and didSet, which run around a change to a stored property. A property can also be private or otherwise restricted with an access level, controlling where code may use it.
Methods: Behavior Attached to Types
A method is a function declared inside a type. Instance methods operate on a particular instance, often reading or changing its properties.
class Book {
var title: String
var isRead = false
init(title: String) {
self.title = title
}
func markAsRead() {
isRead = true
}
}
let book = Book(title: "A Swift Guide")
book.markAsRead()
Here, markAsRead() changes the state of the particular book instance. The parentheses indicate a method call. Methods can accept parameters and return values, just like other functions:
func summary() -> String {
"\(title) has been read: \(isRead)"
}
Swift also has type methods, declared with static or, in some class contexts, class. These belong to the type itself rather than a particular instance. For example, a type method might provide a general rule or utility that does not depend on one book’s state.
Classes, Instances, and Reference Semantics
Declaring a class does not create an instance. Calling its initializer does:
let firstBook = Book(title: "A Swift Guide")
let secondBook = firstBook
Because a class is a reference type, assigning firstBook to secondBook copies the reference, not an independent copy of the object. Both names refer to the same instance. If a mutable property changes through one reference, reading it through the other reflects that change.
This differs from a struct, which is a value type. Assigning a struct value generally gives the new variable its own value, so changes to one copy do not change the other. Swift uses value types extensively, including for many standard-library types such as arrays and strings. Classes are useful when shared identity or reference behavior is needed, but a class is not automatically the right choice for every model.
Choosing Between var, let, Classes, and Structs
These choices answer different questions. var versus let determines whether a binding can be reassigned. Class versus struct determines how instances behave when assigned or passed around.
- Use
letwhen a value or reference should not be reassigned; prefer it unless reassignment is needed. - Use
varwhen the binding itself must be updated. - Use a class when reference identity, shared mutable state, or class inheritance is important.
- Consider a struct for a value that should behave like an independent piece of data, especially when copying it should not create shared identity.
- Use properties for data and derived values; use methods for actions or operations associated with a type.
These are design guidelines rather than strict rules. Swift frameworks and APIs may require a particular kind of type, and a type’s intended behavior should guide the decision.
Common Beginner Misunderstandings
- A property is not the same as a variable declaration. A property is a named value belonging to a type or instance;
varandletare keywords used to declare mutable and constant bindings. - A class is not an object instance. The class declaration defines the type; initialization creates an instance.
letdoes not always freeze an object. It prevents reassignment of the binding. A referenced class instance can still have mutable properties.- A method is not necessarily a property. Methods perform operations and are called with parentheses; properties provide or calculate values.
- Swift does not use one universal class-only model. Structs and enums are first-class tools, and many everyday types are value types.
Frequently Asked Questions
What is the difference between a variable and a property in Swift?
A variable is a mutable binding declared with var. A property is data associated with a type or instance; it may be declared with var if mutable or let if constant.
What is a method in Swift?
A method is a function declared inside a class, struct, or enum. Instance methods work with an instance, while type methods are called on the type.
Are Swift classes reference types?
Yes. Class instances have reference semantics: assignments copy a reference to the instance, so multiple references can point to the same object.
Should I use a class or a struct in Swift?
Use a class when shared identity, reference behavior, or inheritance is needed. Consider a struct when values should be independent copies. The requirements of the design or API may also determine the choice.
Can a Swift property calculate its value?
Yes. A computed property uses a getter to provide a value when accessed, rather than storing that result as its own independent value.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.