SwiftUI view with optional default parameter

Viewed 3822

I am trying to replicate the way we can create a function with a default optional parameter in swiftui.

func greet(_ person: String, nicely: Bool = true) {
    if nicely == true {
        print("Hello, \(person)!")
    } else {
        print("Oh no, it's \(person) again...")
    }
}

Which could be called in two different ways

greet("Taylor")
greet("Taylor", nicely: false)

Is it possible to create a SwiftUI view with this same logic? I would like to create a component that has a 'default optional' parameter so I could call it as:

DividerItem(...)
DividerItem(..., isBold: true)

Many thanks!

2 Answers

Here you go... just define the variables of your View, give them default and you can call them with two different intializations

struct ContentView: View {
    
    var body : some View {
        DividerItem(text: "Hello World", isBold: true)
        DividerItem(text: "Hello Second World")
    }
}


struct DividerItem : View {
    
    var text : String
    var isBold = false
    
    var body : some View {
        Text(text)
            .fontWeight(self.isBold ? .bold : .medium)
    }
}

You can create a custom initialiser for your view

struct DividerItem : View {
    var isBold: Bool
    // other properties

    init(/* other params */ isBold: Bool = false) {
        self.isBold = isBold
    }

    var body: some View {
        //....
    }
}

and then call it with or without the boolean parameter

DividerItem(/* other params */)
DividerItem(/* other params */ isBold: true)
Related