As OOPer showed, there are lots of options here; the best choice really depends on your exact needs. If you post examples of your specific requirements, we can probably suggest more options.
Returning to Albinus’s example, they wrote
But this gets tedious if the struct has a lot of different properties that I want to modify at the same time.
and, yes, they’re right, that can get tedious. However, there are ways to address it within the language already. For example, consider this function:
func scope<T, Result>(inout value: T, body: (inout T) throws -> Result) rethrows -> Result {
return try body(&value)
}
which calls
body
with the specified
inout
parameter, allowing it to modify arbitrary fields in
value
. Consider these basic structures:
struct Colour {
var red: Float
var green: Float
var blue: Float
static var red = Colour(red: 1.0, green: 0.0, blue: 0.0)
static var white = Colour(red: 1.0, green: 1.0, blue: 1.0)
static var blue = Colour(red: 1.0, green: 0.0, blue: 1.0)
}
var france: [Colour] = [.blue, .white, .red]
var italy = france
Here’s an example of how to use this to bulk modify the properties of a struct:
scope(&italy[0]) {
$0.red = 0.0
$0.green = 1.0
$0.blue = 0.0
}
There have been a number of proposals to add direct support for this sort of thing to the language but this hasn’t happened yet. You can get an idea for the sort of interest in this by looking at the list of thread references in the comments at the bottom of SR-160. If you’d like to get involved, head on over to swift-evolution.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"