struct CustomView: View {
var title: String
var color: Color = .black
var body: some View {
Text(title)
.foregroundColor(color)
}
}
struct FooView: View {
var body: some View {
CustomView(title: "Title")
CustomView(title: "Hello", color: .red)
}
}
Swift synthesizes memberwise initializers by default. That means you get an initializer that accepts values for each of the struct’s properties for free. You don't have to write one manually.
If any properties have default values, the generated initializer will use those as default values for the arguments.
If you want your own initializer and you want to keep the generated initializer, write your own one in an extension on the type.
Update: As pointed out by swiftPunk, this doesn't give you two init functions, so if you need to do that:
struct CustomView: View {
let title: String
var color: Color = .black
var body: some View {
Text(title)
.foregroundColor(color)
}
}
extension CustomView {
init(title: String) {
self.title = title
}
}
Now you actually have two actual functions you can use if you need that (maybe you want to compose them or something)
let f1 = CustomView.init(title:)
let f2 = CustomView.init(title:color:)
You can make title let
instead of var
if you like, but view structs are always recomputed anyway.