Types of Properties in Swift

Ngo Minh Tri
3 min readAug 16, 2023

--

In Swift, you’ve got different kinds of properties to use in your classes, structs, and enums. In case, you’re up for some detailed info, you can check out the official guide at https://docs.swift.org/swift-book/documentation/the-swift-programming-language/properties/.

However, if you just want the quick scoop, here are the main types of properties with simple explanations and examples.

1. Stored Property

These are properties that store values directly within an instance. They can be constants (declared with `let`) or variables (declared with `var`).

struct Person {
var name: String
}

2. Computed Property

Computed properties don’t store a value themselves; instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly. They are calculated on-the-fly when accessed.

struct Circle {
var radius: Double

// Computed property
var area: Double {
return Double.pi * radius * radius
}
}

// Usage
let circle = Circle(radius: 5.0)
print(circle.area) // Output: 78.53981633974483

3. Lazy Stored Property

These properties are computed only when they are first accessed. They are marked with the `lazy` keyword and are useful for delaying expensive calculations until needed.

class ImageLoader {
lazy var imageData: Data = {
// Simulating image loading
return Data()
}
}

4. Type Property

Type properties belong to the type itself rather than to instances of the type.

  • They are declared using static keyword for classes.
  • The static or class keyword for structs and enums. class type properties can also be overridden by subclasses.
struct MathConstants {
static let pi = 3.14159
}

5. Property Observers

You can add observers to a property to respond to changes in its value. There are two types:

  • willSet is called just before the value is set.
  • didSet is called immediately after the value is set.
class TemperatureSensor {
var temperature: Double = 0 {
willSet {
print("Temperature will change from \(temperature) to \(newValue)")
}

didSet {
print("Temperature changed from \(oldValue) to \(temperature)")
}
}
}

// Usage
let temperatureSensor = TemperatureSensor()
temperatureSensor.temperature = 25.0

// Output:
// Temperature will change from 0.0 to 25.0
// Temperature changed from 0.0 to 25.0

6. Global Variables and Local Variables

These are properties defined at the global or local scope, respectively. Global variables are properties declared outside any type, and local variables are properties declared within a function or closure.

// Global variable
let appName = "MyApp"

// Local variable
func calculateTax() {
let income = 50000.0
let taxRate = 0.2
let taxAmount = income * taxRate
print("Tax amount: \(taxAmount)")
}

// Usage
let tax = calculateTax() // Output: 10000.0

7. Property Wrapper

Allow you to encapsulate the behavior of property access and modification. They are declared using the `@` symbol followed by the name of the property wrapper type. Property wrappers can simplify property management by adding custom logic such as validation, transformation or synchronization.

import Foundation

@propertyWrapper
struct CharacterLimit {
private var value: String = ""
private let limit: Int

init(limit: Int) {
self.limit = limit
}

var wrappedValue: String {
get { value }
set {
if newValue.count <= limit {
value = newValue
} else {
print("Exceeded character limit! Truncating to \(limit) characters.")
let index = newValue.index(newValue.startIndex, offsetBy: limit)
value = String(newValue.prefix(upTo: index))
}
}
}
}

struct Post {
@CharacterLimit(limit: 60)
var content: String

init(wrappedValue: String) {
self.content = wrappedValue
}
}

var post = Post(wrappedValue: "This is a test post with more than 140 characters. This sentence should get truncated.")
// Output: "Exceeded character limit! Truncating to 60 characters."

print(post.content)
// Output: "This is a test post with more than 140 characters. This sent"

8. Subscripts

While not exactly properties, subscripts allow you to access elements of a collection, list, or sequence type using a shorthand syntax.

struct TimesTable {
let multiplier: Int

subscript(index: Int) -> Int {
return multiplier * index
}
}

// Usage
let timesTable = TimesTable(multiplier: 3)
print(timesTable[5]) // Output: 15

Thank you and happy coding 👏 👏

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ngo Minh Tri
Ngo Minh Tri

Written by Ngo Minh Tri

Wherever you go, go with all your heart.

No responses yet

Write a response