Mobile Development
Swift
Subjective
Oct 04, 2025
What are keypaths in Swift and how are they used?
Detailed Explanation
Keypaths provide a way to reference properties as first-class values in Swift.\n\n• **Basic Syntax:**\n\nstruct Person {
\n let name: String\n let age: Int\n}\n\nlet person = Person(name: "Alice", age: 30)\n\n// Keypath creation\nlet nameKeyPath = \Person.name\nlet ageKeyPath = \Person.age\n\n// Accessing values\nlet name = person[keyPath: nameKeyPath] // "Alice"\nlet age = person[keyPath: ageKeyPath] // 30\n\n\n• **Types of Keypaths:**\n\n// ReadOnly keypath\nlet readOnlyPath: KeyPath = \.name\n\n// Writable keypath\nvar mutablePerson = Person(name: "Bob", age: 25)\nlet writablePath: WritableKeyPath = \.age\nmutablePerson[keyPath: writablePath] = 26\n\n// Reference writable (for classes)\nclass MutablePerson {
\n var name: String\n init(name: String) { self.name = name }\n}\nlet refPath: ReferenceWritableKeyPath = \.name\n\n\n• **Practical Applications:**\n\n// Sorting with keypaths\nlet people = [Person(name: "Alice", age: 30), Person(name: "Bob", age: 25)]\nlet sortedByAge = people.sorted(by: \.age)\nlet sortedByName = people.sorted(by: \.name)\n\n// SwiftUI bindings\nstruct ContentView: View {\n @State var person = Person(name: "Alice", age: 30)\n \n var body: some View {\n TextField("Name", text: $person.name)\n }\n}\n\n\n• **Benefits:**\n• Type-safe property references\n• Functional programming patterns\n• SwiftUI data binding\n• Generic algorithms
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts