Search code examples
swiftswiftui

SwiftUI view with optional default parameter


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!


Solution

  • 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)
        }
    }