示例工程 17-reflection-keypaths
17-reflection-keypaths/Sources/Ch17Demo/App.swift
import Ch17Kit
@main
struct Ch17Demo {
static func main() {
var person = Person(
name: "ada",
age: 36,
address: Address(city: "Beijing", zip: "100000"),
nickname: "a"
)
print("[17.1] 类型 = \(MirrorLab.typeName(person))")
print("[17.1] children = \(MirrorLab.labels(person))")
print("[17.1] 值 = \(MirrorLab.describe(person))")
print("[17.2] 计算属性在 Mirror 中 = \(MirrorLab.labels(person).contains("displayName"))")
print("[17.2] 嵌套形状 = \(MirrorLab.shape(person))")
print("[17.3] keyPath 读 = \(KeyPathLab.value(person, at: \.name))")
KeyPathLab.set(&person, \.age, to: 37)
print("[17.3] keyPath 写后 age = \(person.age)")
let people = [
Person(name: "bob", age: 20, address: Address(city: "A", zip: "1"), nickname: nil),
Person(name: "ann", age: 30, address: Address(city: "B", zip: "2"), nickname: nil),
]
print("[17.4] 按 age 排序 = \(KeyPathLab.sortedByAge(people).map(\.name))")
print("[17.4] 存储的 KeyPath 值 = \(KeyPathLab.value(person, at: KeyPathLab.ageKeyPath))")
var settings = StringSettings(["theme": "light"])
print("[17.5] dynamicMember 读 = \(settings.theme ?? "nil")")
settings.theme = "dark"
settings.font = "mono"
print("[17.5] dynamicMember 写后 = \(settings.allKeys)/\(settings.theme ?? "nil")")
print("[17.5] 缺失键 = \(settings.missing ?? "nil")")
print("[17.6] dynamicCallable = \(Sum()(1, 2, 3, 4))")
let node = Node(value: 1)
let same = node
let other = Node(value: 1)
print("[17.7] 不同实例数 = \(IdentityLab.distinctCount([node, same, other]))")
print("[17.7] 包含同一实例 = \(IdentityLab.containsSameInstance([node, other], as: same))")
print(
"[17.8] MemoryLayout<KeyPath<Person, Int>> = \(MemoryLayout<KeyPath<Person, Int>>.size) 字节"
)
print("[17.8] MemoryLayout<StringSettings> = \(MemoryLayout<StringSettings>.size) 字节")
}
}