This is a common pattern in some other languages. Is there a best way to do it in Swift? I like structs but you run into a problem with immutable temporaries.
I suppose the options to fix the error below are:
- Use a class.
- Make
changeStuff()
non-mutating and return a newBuilder
instead. I worry about efficiency.
In this case, should the compiler allow you to mutate the temporary?
struct Builder {
var stuff: Int = 0
mutating func changeStuff() -> Builder {
stuff += 1
return self
}
}
func startBuilder() -> Builder {
Builder(stuff: 0)
}
// Okay:
var b = startBuilder()
b.changeStuff()
let result = b.stuff
print(result)
// But fluid syntax doesn't work:
// Cannot use mutating member on immutable value: 'startBuilder' returns immutable value
let result2 = startBuilder().changeStuff().stuff
print(result2)