Lesson 51Structs
Struct Basics
What is a Struct?
A struct (structure) is a custom data type that lets you group related values together. Structs are value types - they get copied when assigned!
Struct Syntax
struct Name {
var property1: Type
var property2: Type
}
var property1: Type
var property2: Type
}
Value Type Behavior
When you assign a struct to a new variable or pass it to a function, a copy is made. Changes to the copy don't affect the original!
Why Use Structs?
Group Data
Organize related values together
Custom Types
Create your own data types
Safe & Fast
Value semantics, lightweight
Built-in Types
String, Int, Array are structs!
Default Values
You can give properties default values. When creating an instance, you can omit those properties or override them!
main.swift
// WHAT IS A STRUCT?
// A struct is a custom data type that groups related values
// Structs are VALUE TYPES (copied when assigned)
// BASIC STRUCT DEFINITION
struct Person {
var name: String
var age: Int
}
// CREATING INSTANCES
var person1 = Person(name: "Alice", age: 25)
var person2 = Person(name: "Bob", age: 30)
print(person1.name) // Alice
print(person2.age) // 30
// ACCESSING & MODIFYING PROPERTIES
person1.age = 26
print(person1.age) // 26
// VALUE TYPE BEHAVIOR
var person3 = person1 // Creates a COPY
person3.name = "Charlie"
print(person1.name) // Alice (unchanged!)
print(person3.name) // Charlie
// STRUCT WITH DIFFERENT PROPERTY TYPES
struct Product {
var name: String
var price: Double
var inStock: Bool
var quantity: Int
}
let laptop = Product(
name: "MacBook Pro",
price: 1999.99,
inStock: true,
quantity: 50
)
print("\(laptop.name): $\(laptop.price)")
// STRUCT WITH DEFAULT VALUES
struct User {
var username: String
var email: String
var isActive: Bool = true // Default value
var loginCount: Int = 0 // Default value
}
// Can omit properties with defaults
let user1 = User(username: "swift_fan", email: "[email protected]")
print(user1.isActive) // true (default)
// Or override them
let user2 = User(
username: "admin",
email: "[email protected]",
isActive: true,
loginCount: 100
)
// WHY USE STRUCTS?
// 1. Group related data together
// 2. Create custom types
// 3. Value semantics (safer in multi-threaded code)
// 4. Lightweight and fast
// COMMON BUILT-IN STRUCTS
// String, Int, Double, Bool, Array, Dictionary
// are all structs in Swift!
let greeting: String = "Hello" // String is a struct!
let numbers: [Int] = [1, 2, 3] // Array is a struct!Try It Yourself!
Create a Book struct with title, author, pages, and isRead properties. Create two book instances!