SWIFT
Swift Struct: Syntax, Usage, and Examples
A Swift struct is a value type that groups related properties and methods into a single entity. Unlike classes, structs are copied when passed around, making them ideal for encapsulating lightweight data models. You can use structs to create reusable, predictable, and efficient data structures in Swift applications.
How to Use Structs in Swift
A struct is defined using the struct
keyword, followed by properties and methods inside curly braces.
struct Person {
var name: String
var age: Int
}
Creating and Initializing a Struct
You can create an instance of a struct by providing values for its properties.
let person = Person(name: "Alice", age: 30)
By default, Swift provides a memberwise initializer for structs, allowing you to assign values directly when creating an instance.
Mutating Structs
Since structs are value types, you must mark a method as mutating
if it modifies properties inside the struct.
struct Counter {
var value: Int
mutating func increment() {
value += 1
}
}
var counter = Counter(value: 0)
counter.increment()
print(counter.value) // Output: 1
This restriction ensures struct instances remain immutable unless explicitly declared as var
.
When to Use Structs in Swift
Structs are a powerful alternative to classes and are particularly useful when working with immutable or copyable data.
Encapsulating Simple Data Models
Structs provide an easy way to encapsulate related data without the complexity of reference types.
struct Rectangle {
var width: Double
var height: Double
func area() -> Double {
return width * height
}
}
let rect = Rectangle(width: 5, height: 10)
print(rect.area()) // Output: 50
Passing Structs to Functions
Structs are copied when passed to functions, preventing unintended modifications to the original data.
func printPersonInfo(person: Person) {
print("\(person.name) is \(person.age) years old.")
}
let bob = Person(name: "Bob", age: 28)
printPersonInfo(person: bob)
Storing Collections of Data
Structs work well with arrays and dictionaries, providing a clean and organized way to handle lists of related objects.
struct Task {
var title: String
var completed: Bool
}
var tasks: [Task] = [
Task(title: "Buy groceries", completed: false),
Task(title: "Walk the dog", completed: true)
]
print(tasks[0].title) // Output: Buy groceries
Examples of Structs in Swift
Appending a Struct to an Array
Adding struct instances to an array allows you to store and manipulate multiple data entries efficiently.
var tasksList: [Task] = []
let newTask = Task(title: "Read a book", completed: false)
tasksList.append(newTask)
print(tasksList.count) // Output: 1
Structs with Computed Properties
Structs support computed properties, which dynamically calculate values based on other properties.
struct Circle {
var radius: Double
var circumference: Double {
return 2 * 3.1416 * radius
}
}
let circle = Circle(radius: 5)
print(circle.circumference) // Output: 31.416
Comparing Structs to Classes
A key difference between structs and classes is how they handle data storage. Structs use value semantics, while classes use reference semantics.
struct UserStruct {
var name: String
}
class UserClass {
var name: String
init(name: String) {
self.name = name
}
}
var structUser1 = UserStruct(name: "Emily")
var structUser2 = structUser1
structUser2.name = "Sophia"
print(structUser1.name) // Output: Emily
var classUser1 = UserClass(name: "Emily")
var classUser2 = classUser1
classUser2.name = "Sophia"
print(classUser1.name) // Output: Sophia
Since structs are copied when assigned to a new variable, structUser1
retains its original value. In contrast, modifying classUser2
affects classUser1
because both reference the same memory location.
Learn More About Structs in Swift
Swift structs support additional features like nested structs, protocol conformance, and dictionary conversion.
Nested Structs
You can define structs inside other structs to group related data logically.
struct Car {
struct Engine {
var horsepower: Int
}
var model: String
var engine: Engine
}
let myCar = Car(model: "Tesla Model 3", engine: Car.Engine(horsepower: 283))
print(myCar.engine.horsepower) // Output: 283
Extending Structs
You can add functionality to an existing struct without modifying its original definition using extensions.
struct Point {
var x: Double
var y: Double
}
extension Point {
func distance(to point: Point) -> Double {
let dx = x - point.x
let dy = y - point.y
return (dx * dx + dy * dy).squareRoot()
}
}
let p1 = Point(x: 0, y: 0)
let p2 = Point(x: 3, y: 4)
print(p1.distance(to: p2)) // Output: 5
Converting a Dictionary to a Struct
You can initialize a struct from a dictionary to work with JSON or API responses.
struct User {
var name: String
var age: Int
init?(dictionary: [String: Any]) {
guard let name = dictionary["name"] as? String,
let age = dictionary["age"] as? Int else {
return nil
}
self.name = name
self.age = age
}
}
let userData: [String: Any] = ["name": "Liam", "age": 25]
if let user = User(dictionary: userData) {
print(user.name) // Output: Liam
}
Converting a Struct to a Dictionary
You can convert a struct back into a dictionary for storage or network transmission.
extension User {
func toDictionary() -> [String: Any] {
return ["name": name, "age": age]
}
}
let user = User(name: "Olivia", age: 22)
print(user.toDictionary()) // Output: ["name": "Olivia", "age": 22]
Using Structs for Configuration
Since structs are immutable by default, they are great for defining configuration settings in an app.
struct AppSettings {
static let apiEndpoint = "https://api.example.com"
static let maxConnections = 5
}
print(AppSettings.apiEndpoint) // Output: https://api.example.com
Best Practices for Using Structs
- Use structs for immutable data or when passing values around should not cause side effects.
- Choose classes instead when dealing with shared, mutable state.
- Store simple models in structs to take advantage of Swift’s automatic memberwise initializer.
- Avoid large structs with many properties, as copying them may impact performance.
- Consider using extensions to organize functionality instead of cluttering struct definitions.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.