Tuples in Swift
Tuples in Swift
A tuple in Swift is a group of values combined into a single compound value. Tuples are useful for temporarily grouping related values, particularly when returning multiple values from a function.
Key Features of Tuples
1. Fixed Size: The number of elements in a tuple is fixed when it is created.
2. Heterogeneous Types: Each element in a tuple can be of a different type.
3. Lightweight: Tuples are simpler than structs or classes and suitable for temporary data.
Defining and Accessing Tuples
1. Creating a Tuple
let person = ("John", 30, true)
print(person) // Output: ("John", 30, true)
2. Accessing Elements by Index
print(person.0) // Output: John
print(person.1) // Output: 30
3. Named Elements
let person = (name: "John", age: 30, isEmployed: true)
print(person.name) // Output: John
print(person.age) // Output: 30
Tuples in Functions
1. Returning Multiple Values
func getUserInfo() -> (name: String, age: Int, isEmployed: Bool) {
return ("Alice", 25, true)
}
let userInfo = getUserInfo()
print(userInfo.name) // Output: Alice
2. Decomposing Tuples
let (name, age, isEmployed) = getUserInfo()
print(name) // Output: Alice
31. Enums with Associated Values
Enums in Swift allow you to define a set of related values. Associated values enhance enums by letting each case store additional data.
Defining Enums with Associated Values
1. Basic Example
enum NetworkRequest {
case success(data: String)
case failure(errorCode: Int)
}
2. Using Associated Values
let response = NetworkRequest.success(data: "Response data")
switch response {
case .success(let data):
print("Success with data: \(data)")
case .failure(let errorCode):
print("Failed with error code: \(errorCode)")
}
// Output: Success with data: Response data
Real-World Example
Handling Multiple File Types
enum MediaType {
case image(fileName: String, resolution: (width: Int, height: Int))
case video(fileName: String, duration: Int)
case text(fileName: String, wordCount: Int)
}
let file = MediaType.image(fileName: "photo.jpg", resolution: (1920, 1080))
switch file {
case .image(let fileName, let resolution):
print("Image \(fileName) with resolution \(resolution.width)x\(resolution.height)")
case .video(let fileName, let duration):
print("Video \(fileName) with duration \(duration) seconds")
case .text(let fileName, let wordCount):
print("Text file \(fileName) with \(wordCount) words")
}
// Output: Image photo.jpg with resolution 1920x1080
32. Structs vs Classes
Structs and classes are two fundamental building blocks in Swift. They both allow you to define custom data types, but they behave differently.
Key Differences Between Structs and Classes
Feature Struct Class
Type Value Type Reference Type
Memory Allocation Stored on the stack Stored on the heap
Inheritance Not supported Supported
Mutability Requires mutating for methods to modify Methods can modify properties freely
Copy Behavior Copies the data Shares a reference
When to Use Structs vs Classes
1. Use Structs When:
• Data is relatively simple and immutable (e.g., Point, Size, Rectangle).
• Copy behavior is desirable.
2. Use Classes When:
• You need inheritance or polymorphism.
• You need reference semantics.
Example Comparison
Struct
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 0, y: 0)
var p2 = p1
p2.x = 5
print(p1.x) // Output: 0 (struct creates a copy)
Class
class Point {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
let p1 = Point(x: 0, y: 0)
let p2 = p1
p2.x = 5
print(p1.x) // Output: 5 (class shares a reference)
33. Properties (Stored, Computed, Observers)
Properties in Swift allow you to store and compute values within structs, classes, or enums.
Types of Properties
1. Stored Properties
• Store constant or variable values.
struct Person {
var name: String
let age: Int
}
let person = Person(name: "Alice", age: 25)
print(person.name) // Output: Alice
2. Computed Properties
• Calculate a value rather than storing it.
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 10, height: 20)
print(rect.area) // Output: 200
3. Property Observers
• Observe and respond to property changes using willSet and didSet.
class Counter {
var count: Int = 0 {
willSet {
print("About to set count to \(newValue)")
}
didSet {
print("Count changed from \(oldValue) to \(count)")
}
}
}
let counter = Counter()
counter.count = 10
// Output:
// About to set count to 10
// Count changed from 0 to 10
34. Methods (Instance, Static, and Class Methods)
Instance Methods
Instance methods belong to a specific instance of a class, struct, or enum.
struct Counter {
var count: Int = 0
mutating func increment() {
count += 1
}
}
var counter = Counter()
counter.increment()
print(counter.count) // Output: 1
Static Methods
Static methods belong to the type itself rather than an instance.
struct Math {
static func square(_ value: Int) -> Int {
return value * value
}
}
print(Math.square(4)) // Output: 16
Class Methods
Class methods, defined with class instead of static, can be overridden in subclasses.
class Shape {
class func description() -> String {
return "I am a shape."
}
}
class Circle: Shape {
override class func description() -> String {
return "I am a circle."
}
}
print(Shape.description()) // Output: I am a shape.
print(Circle.description()) // Output: I am a circle.
Comments
Post a Comment