Swift Structure Using the struct Keyword
A structure in Swift is a custom data type that groups related properties and methods under one name. Structures are declared with the struct keyword and are commonly used to represent values such as coordinates, products, users, settings, and other related data.
Swift structures are value types. When a structure instance is assigned to another variable or passed to a function, Swift works with a separate value rather than sharing the same instance.
Swift struct Syntax
The following syntax declares a structure in Swift.
struct structureName {
// structure_body
}
Here, structureName is the name used to create and reference instances of the structure.
The structure body can contain stored properties, computed properties, initializers, methods, type properties, and type methods.
Declare Properties in a Swift Structure
Properties store the data associated with each structure instance. Use var for a property that may change and let for a property that must remain constant after initialization.
struct Book {
let title: String
var pageCount: Int
}
In this example, the title cannot be changed after a Book value is created, while pageCount can be updated when the instance is stored in a variable.
Example 1 – Create and Initialize a Swift Structure
The following example defines a structure named car with properties for the brand, model name, and seating capacity. A custom initializer assigns values to all three properties.
main.swift
struct car {
var brand: String
var name: String
var capacity: Int
init(brand: String, name: String, capacity: Int) {
self.brand = brand
self.name = name
self.capacity = capacity
}
}
let car1 = car(brand: "Hyundai", name: "Creta", capacity: 5)
print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")
Output
Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5
The expression car(brand:name:capacity:) calls the initializer and returns a new structure value. Individual properties are accessed with dot syntax, such as car1.brand.
Swift Memberwise Initializer
When a structure does not declare a custom initializer, Swift can automatically provide a memberwise initializer for its stored properties.
struct Rectangle {
var width: Double
var height: Double
}
let rectangle = Rectangle(width: 8.0, height: 4.0)
print(rectangle.width)
print(rectangle.height)
Output
8.0
4.0
Declaring a custom initializer can change which automatically generated initializers are available. Define every initializer that callers need when custom initialization logic is required.
Example 2 – Swift Structure Properties with Default Values
A stored property can be assigned a default value directly in the structure declaration. The initializer then needs to assign only the properties that do not already have values.
main.swift
struct car {
var brand: String
var name: String
var capacity = 5
init(brand: String, name: String) {
self.brand = brand
self.name = name
}
}
let car1 = car(brand: "Hyundai", name: "Creta")
print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")
Output
Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5
The capacity property receives the value 5 unless another initializer or later assignment supplies a different value.
Example 3 – Swift Structure with Multiple Initializers
A structure may declare multiple initializers with different parameter lists. Each initializer must ensure that every stored property has a value before initialization finishes.
main.swift
struct car {
var brand: String
var name: String
var capacity: Int
init(brand: String, name: String) {
self.brand = brand
self.name = name
self.capacity = 5
}
init(brand: String, name: String, capacity: Int) {
self.brand = brand
self.name = name
self.capacity = capacity
}
}
let car1 = car(brand: "Hyundai", name: "Creta")
print("Car details\n-----------")
print("Brand is \(car1.brand)")
print("Name is \(car1.name)")
print("Seating capacity is \(car1.capacity)")
let car2 = car(brand: "Toyota", name: "Innova", capacity: 7)
print("\nCar details\n-----------")
print("Brand is \(car2.brand)")
print("Name is \(car2.name)")
print("Seating capacity is \(car2.capacity)")
Output
Car details
-----------
Brand is Hyundai
Name is Creta
Seating capacity is 5
Car details
-----------
Brand is Toyota
Name is Innova
Seating capacity is 7
The first initializer assigns a fixed capacity of 5. The second initializer accepts a capacity argument, allowing the caller to create a structure with another value.
Add Methods to a Swift Structure
A Swift structure can contain instance methods that operate on its properties.
struct Circle {
var radius: Double
func area() -> Double {
return Double.pi * radius * radius
}
}
let circle = Circle(radius: 3.0)
print(circle.area())
The area() method reads the instance’s radius property and returns the calculated area.
Modify Structure Properties with a mutating Method
Instance methods cannot modify a structure’s stored properties unless the method is marked with the mutating keyword.
struct Counter {
var value = 0
mutating func increment() {
value += 1
}
}
var counter = Counter()
counter.increment()
print(counter.value)
Output
1
The instance is declared with var because a structure stored in a let constant cannot have its variable properties changed.
Swift Structures Are Value Types
Assigning one structure value to another variable creates an independent value. A change made through one variable does not modify the other variable.
struct Point {
var x: Int
var y: Int
}
var firstPoint = Point(x: 10, y: 20)
var secondPoint = firstPoint
secondPoint.x = 50
print(firstPoint.x)
print(secondPoint.x)
Output
10
50
Changing secondPoint.x does not change firstPoint.x because each variable contains its own Point value.
Swift struct and class Differences
Structures and classes can both define properties, methods, initializers, subscripts, and protocol conformances. Their main difference is how instances are represented and shared.
- A structure is a value type, while a class is a reference type.
- Structure assignment produces an independent value, while class assignment can create another reference to the same instance.
- Classes support inheritance; structures do not.
- Classes can define deinitializers; structures cannot.
- Structures receive an automatic memberwise initializer when eligible.
Use a structure when the data represents a value and independent copies are appropriate. Use a class when identity, shared mutable state, inheritance, or reference semantics are required.
Swift Structure Naming and Mutation Guidelines
- Name structure types with UpperCamelCase, such as
Car,UserProfile, orNetworkSettings. - Name properties and methods with lowerCamelCase.
- Use
letfor structure instances that should not be modified. - Use
varwhen a stored property or a mutating method must change the instance. - Provide default property values when they represent a meaningful default state.
- Use custom initializers when validation or additional setup is required.
Frequently Asked Questions About Swift Structures
What is a struct in Swift?
A struct is a custom value type that can contain properties, methods, initializers, and protocol conformances.
Does Swift automatically create an initializer for a struct?
Swift normally provides a memberwise initializer for a structure’s stored properties when no conflicting custom initializer is declared.
Can a Swift struct contain methods?
Yes. A structure can define instance methods and type methods. A method that changes stored properties must be marked mutating.
Why can I not modify a property of a let struct instance?
Because structures are value types, declaring the entire instance with let makes that value immutable, including properties declared with var.
When should I use a struct instead of a class in Swift?
Use a structure when the type represents a value, does not require inheritance, and should have independent copies when assigned or passed to functions.
TutorialKart.com