Easiest examples of Properties in Swift

Rahul Goel
2 min readDec 26, 2023
Apple Swift 5.0

Properties in Swift are variables or constants that are associated with a particular class, structure, or enumeration. They define the characteristics and values associated with instances of these types.

Here are some common questions and information related to properties in Swift.

1. What are Stored Properties in Swift?

  • Stored properties store constant and variable values as part of an instance.
  • They are declared with var (variable) or let (constant) keywords.
struct Point {
var x: Double
var y: Double
}

2. What is a Computed Property?

  • Computed properties do not store a value but provide a getter and an optional setter.
  • They are declared with var and contain a code block to calculate the value.
struct Circle {
var radius: Double
var area: Double {
return Double.pi * radius * radius
}
}

3. What is a Property Observer?

  • Property observers observe and respond to changes in a property’s value.
  • They are implemented using willSet and didSet keywords.
var score: Int = 0 {
willSet {
print("Score will be set to \(newValue)")
}
didSet {
print("Score was set to \(score) (previously \(oldValue))")
}
}

4. What is Lazy Initialization?

  • The lazy keyword is used for properties that are initialized only when accessed for the first time.
  • Useful for delaying the creation of an object until it’s actually needed.
class DataManager {
lazy var data: [String] = {
// Expensive data loading code
return ["Data1", "Data2", "Data3"]
}()
}

5. What is a Type Property?

  • Type properties belong to the type itself rather than instances of the type.
  • They are declared with the static keyword.
struct MathUtility {
static let pi = 3.14159
}

6. What is Property Wrappers?

  • Property wrappers provide a way to add custom behavior to property access.
  • Introduced with Swift 5.1, they are defined using the @propertyWrapper attribute.

In this example, we’ll create a Capitalize property wrapper that automatically capitalizes the string value it wraps.

@propertyWrapper
struct Capitalize {
private(set) var value: String = ""

init(wrappedValue: String) {
self.value = wrappedValue.capitalized
}

var wrappedValue: String {
get { return value }
set { value = newValue.capitalized }
}
}

struct User {
@Capitalize var firstName: String
@Capitalize var lastName: String
}

var user = User(firstName: "rahul", lastName: "goel")

print(user.firstName) // "Rahul"
print(user.lastName) // "Goel"

Follow me Rahul Goel for more updates.

--

--

Rahul Goel

Computer Science Enthusiast | 11+ Year of Software Evolution | @Sharechat, Groupon, Paytm, Myntra https://www.linkedin.com/in/therahulgoel/