Extensions for Swift KeyPaths. Currently this package contains helpers for managing KeyPaths with Optional values, if you need extensions for enums, take a look at pointfreeco/swift-case-paths
struct Root {
struct Property {
var intValue: Int = 0
}
var optionalProperty: Property?
init(_ value: Int?) {
self.optionalProperty = value.map(Property.init(intValue:))
}
}// available out-of-the-box, recommended way when available
let kp_expression: KeyPath<Root, Int?> = \Root.optionalProperty?.intValue// if you have 2 arbitrary paths
// and kp_1.Value.Type doesn't match kp_2.Value.Type exactly
// (Optionality causes mismatch in that case)
let kp_1: KeyPath<Root, Property?> = \Root.optionalProperty
let kp_2: KeyPath<Property, Int> = \Property.intValue
// `kp_1.appending(path: kp_2)` is not available out-of-the-box
let kp_combined: KeyPath<Root, Int?> = kp_1.appending(kp_2)
// unwrapping is not available out-of-the-box
let kp_unwrapped: KeyPath<Root, Int> = kp_combined.unwrapped(with: 0)
// ⚠️ tho unwrapped paths shouldn't be combined for reference typesNote
Take a look at tests for more examples. Also keep your eye on doc comments for more info.
You can add KeypathsExtensions to an Xcode project by adding it as a package dependency.
- From the File menu, select Swift Packages › Add Package Dependency…
- Enter
"https://github.com/capturecontext/swift-keypaths-extensions"into the package repository URL text field - Choose products you need to link them to your project.
If you use SwiftPM for your project structure, add KeyPathsExtensions to your package file.
.package(
url: "[email protected]:capturecontext/swift-keypaths-extensions.git",
.upToNextMinor(from: "0.0.1")
)or via HTTPS
.package(
url: "https://github.com:capturecontext/swift-keypaths-extensions.git",
.upToNextMinor("0.0.1")
)Do not forget about target dependencies:
.product(
name: "KeyPathsExtensions",
package: "swift-keypaths-extensions"
)This library is released under the MIT license. See LICENSE for details.