Class và Object trong Swift
1. Giới thiệu
Class là reference type, hỗ trợ kế thừa và deinitializers.
2. Khai báo Class
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func introduce() {
print("Tôi là \(name), \(age) tuổi")
}
}
let person = Person(name: "Alice", age: 25)
person.introduce()3. Reference Type Semantics
class Point {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
let point1 = Point(x: 10, y: 20)
let point2 = point1 // Same reference
point2.x = 100
print(point1.x) // 100 (changed!)
print(point2.x) // 1004. Deinitializer
class FileHandle {
let filename: String
init(filename: String) {
self.filename = filename
print("Opening \(filename)")
}
deinit {
print("Closing \(filename)")
}
}
var handle: FileHandle? = FileHandle(filename: "test.txt")
handle = nil // Prints: Closing test.txt5. Computed Properties
class Circle {
var radius: Double
init(radius: Double) {
self.radius = radius
}
var area: Double {
get { .pi * radius * radius }
}
var diameter: Double {
get { radius * 2 }
set { radius = newValue / 2 }
}
}6. Property Observers
class StepCounter {
var steps: Int = 0 {
willSet {
print("About to set to \(newValue)")
}
didSet {
print("Changed from \(oldValue) to \(steps)")
}
}
}
let counter = StepCounter()
counter.steps = 1007. Lazy Properties
class DataLoader {
lazy var data: [String] = {
print("Loading data...")
return ["a", "b", "c"]
}()
}
let loader = DataLoader()
// Data chưa được load
print(loader.data) // Now loading...8. Static vs Class Members
class Parent {
static var staticProp = "Static"
class var classProp: String { "Class" }
static func staticMethod() {}
class func classMethod() {} // Can be overridden
}
class Child: Parent {
override class var classProp: String { "Overridden" }
override class func classMethod() {}
// static không thể override
}9. Identity Operators
let a = Person(name: "Alice", age: 25)
let b = a
let c = Person(name: "Alice", age: 25)
print(a === b) // true (same instance)
print(a === c) // false (different instances)
print(a !== c) // true10. Ví dụ thực tế
class ViewController: UIViewController {
private let viewModel: ViewModel
lazy var tableView: UITableView = {
let tv = UITableView()
tv.delegate = self
tv.dataSource = self
return tv
}()
init(viewModel: ViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) not implemented")
}
deinit {
print("ViewController deallocated")
}
}📝 Tóm tắt
- Class là reference type
- Bắt buộc có initializer
deinitcho cleanup===và!==so sánh identitylazycho delayed initializationclasskeyword cho overridable statics
Last updated on
Swift