Skip to Content
Swift📘 Ngôn ngữ SwiftStatic Properties & Methods

Static Properties và Methods trong Swift

1. Giới thiệu

Static properties và methods thuộc về type (class/struct), không phải instance.

2. Static trong Struct

struct AppConfig { static let appName = "MyApp" static let version = "1.0.0" static var isDebugMode = false static func printInfo() { print("\(appName) v\(version)") } } // Truy cập qua type, không qua instance print(AppConfig.appName) // MyApp print(AppConfig.version) // 1.0.0 AppConfig.isDebugMode = true AppConfig.printInfo() // MyApp v1.0.0

3. Static trong Class

class Counter { static var totalCount = 0 var instanceCount = 0 init() { Counter.totalCount += 1 instanceCount = Counter.totalCount } static func reset() { totalCount = 0 } } let c1 = Counter() // totalCount = 1 let c2 = Counter() // totalCount = 2 let c3 = Counter() // totalCount = 3 print(Counter.totalCount) // 3 print(c1.instanceCount) // 1 print(c3.instanceCount) // 3

4. Class vs Static (trong Class)

class Animal { // static: không thể override static var species = "Animal" // class: có thể override class var description: String { "An animal" } class func makeSound() { print("...") } } class Dog: Animal { // Override class property override class var description: String { "A dog" } // Override class method override class func makeSound() { print("Woof!") } } print(Animal.description) // An animal print(Dog.description) // A dog Dog.makeSound() // Woof!

5. Singleton Pattern

class DatabaseManager { static let shared = DatabaseManager() private init() { // Private init ngăn tạo instance mới print("Database initialized") } func query(_ sql: String) -> [String] { print("Executing: \(sql)") return [] } } // Sử dụng let db = DatabaseManager.shared db.query("SELECT * FROM users") // DatabaseManager() // Error: init is private

6. Factory Methods

struct Color { var red: Double var green: Double var blue: Double // Static factory methods static let white = Color(red: 1, green: 1, blue: 1) static let black = Color(red: 0, green: 0, blue: 0) static let red = Color(red: 1, green: 0, blue: 0) static func gray(brightness: Double) -> Color { Color(red: brightness, green: brightness, blue: brightness) } static func random() -> Color { Color( red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1) ) } } let bg = Color.white let text = Color.black let dimGray = Color.gray(brightness: 0.3) let randomColor = Color.random()

7. Utility Classes

struct MathUtils { static let pi = 3.14159 static let e = 2.71828 static func square(_ x: Double) -> Double { x * x } static func cube(_ x: Double) -> Double { x * x * x } static func clamp(_ value: Double, min: Double, max: Double) -> Double { Swift.min(Swift.max(value, min), max) } } print(MathUtils.square(5)) // 25.0 print(MathUtils.clamp(150, min: 0, max: 100)) // 100.0

8. Configuration và Constants

struct APIEndpoints { static let baseURL = "https://api.example.com" static var users: String { baseURL + "/users" } static var posts: String { baseURL + "/posts" } static var comments: String { baseURL + "/comments" } static func user(id: Int) -> String { "\(users)/\(id)" } } print(APIEndpoints.users) // https://api.example.com/users print(APIEndpoints.user(id: 5)) // https://api.example.com/users/5 struct Theme { static let primaryColor = Color.blue static let secondaryColor = Color.gray static let fontSize: CGFloat = 16 static let cornerRadius: CGFloat = 8 }

9. Trong Enum

enum Direction: String { case north, south, east, west static let all: [Direction] = [.north, .south, .east, .west] static func random() -> Direction { all.randomElement()! } static var defaultDirection: Direction { .north } } print(Direction.all) // [north, south, east, west] print(Direction.random()) // Random direction

10. Ví dụ thực tế: Analytics

class Analytics { static let shared = Analytics() private init() {} private(set) static var eventCount = 0 static func track(event: String, properties: [String: Any] = [:]) { eventCount += 1 print("📊 Event #\(eventCount): \(event)") for (key, value) in properties { print(" \(key): \(value)") } } static func reset() { eventCount = 0 } } Analytics.track(event: "app_open") Analytics.track(event: "button_tap", properties: ["button": "login"]) print("Total events: \(Analytics.eventCount)")

📝 Tóm tắt

  • static - thuộc về type, không thể override
  • class - thuộc về type, có thể override (chỉ trong class)
  • Truy cập qua TypeName.property hoặc TypeName.method()
  • Dùng cho: constants, factory methods, singleton, utilities
  • Self (viết hoa) để refer đến type hiện tại
Last updated on