How to achieve a similar chain style with struct
, do comment if it's a duplicate.
class Employee {
var name: String?
var designation: String?
func name(_ name: String) -> Employee {
self.name = name
return self
}
func designation(_ designation: String) -> Employee {
self.designation = designation
return self
}
}
/// Usage
let emp = Employee()
.name("Speedy")
.designation("iOS Enigineer")
print(emp.designation)
CodePudding user response:
You should call the initialiser of the struct and pass it the given value:
struct Employee {
var name: String?
var designation: String?
func name(_ name: String) -> Employee {
.init(name: name, designation: self.designation)
}
func designation(_ designation: String) -> Employee {
.init(name: self.name, designation: designation)
}
}
If all the methods that you are chaining are boring property setters, you might as well just call the automatically generated initialisers:
// either parameter can be omitted!
Employee(name: "...", designation: "...")
This sort of chaining is only really useful when there are more complicated things going on with your properties. For example, when 2 properties must be set at the same time, or if you require generic parameters when setting those properties. For a good example of this, see how SwiftUI does this.
See also: Builder pattern set method in swift