In the last episode we explored how functional setters allow us to dive deeper into nested structures to perform transformations while leaving everything else in the structure fixed. We played around with some toy examples, like nested tuples and arrays, and we showed off some pretty impressive stuff, but at the end of the day we aren’t typically transforming tuples. Instead, we have real world data with structs. We want to bring all the ideas from the previous episode into the world of structs so that we can transform a deeply nested struct in a simple, expressive manner. To do this, we are going to leverage Swift’s key paths!
Here we have a few related structs:
struct Food {
var name: String
}
struct Location {
var name: String
}
struct User {
var favoriteFoods: [Food]
var location: Location
var name: String
}
let user = User(
favoriteFoods: [
Food(name: "Tacos"),
Food(name: "Nachos")
],
location: Location(name: "Brooklyn"),
name: "Blob"
)