Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI view with optional default parameter

Tags:

swift

swiftui

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!

like image 274
jmrueda Avatar asked May 15 '26 09:05

jmrueda


1 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)
    }
}
like image 127
davidev Avatar answered May 18 '26 02:05

davidev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!