Swift Modifiers
Access control and visibility modifiers in Swift
🔒 What are Swift Modifiers?
Swift modifiers control access levels and visibility of classes, properties, and methods. They help encapsulate code and define what can be accessed from different parts of your application.
// Access control example
public class User {
private var password: String
public var username: String
public init(username: String, password: String) {
self.username = username
self.password = password
}
}
Output:
User class with public username and private password
Access Control Levels
public
Accessible from anywhere
public var name = "Swift"
internal
Accessible within the same module
internal func calculate() { }
fileprivate
Accessible within the same file
fileprivate var helper = "data"
private
Accessible only within declaration
private var secret = "hidden"
🔹 Property Modifiers
Swift provides various modifiers for properties:
class BankAccount {
// Read-only property
private(set) var balance: Double = 0.0
// Lazy property
lazy var accountNumber = generateAccountNumber()
// Static property
static let bankName = "Swift Bank"
// Computed property
var formattedBalance: String {
return "$\(balance)"
}
func deposit(_ amount: Double) {
balance += amount
}
}
Output:
BankAccount with controlled access to balance property
🔹 Method Modifiers
Control how methods can be accessed and overridden:
class Vehicle {
// Can be overridden
open func start() {
print("Vehicle starting...")
}
// Cannot be overridden
final func stop() {
print("Vehicle stopped")
}
// Class method
class func getType() -> String {
return "Vehicle"
}
// Static method
static func getWheels() -> Int {
return 4
}
}
Output:
Vehicle starting...
Vehicle stopped
🔹 Inheritance Modifiers
Control class inheritance and method overriding:
// Open class - can be subclassed anywhere
open class Animal {
open func makeSound() {
print("Some sound")
}
}
// Public class - can be subclassed in same module
public class Dog: Animal {
// Override parent method
override public func makeSound() {
print("Woof!")
}
// Final method - cannot be overridden
final func wagTail() {
print("Wagging tail")
}
}
// Final class - cannot be subclassed
final class Robot {
func beep() {
print("Beep beep!")
}
}
Output:
Woof!
Wagging tail
Beep beep!