.if(let:then:)
extension View {
/// usage: `view.if(let: value) { (view, value) in ... }`
@ViewBuilder func if<Value, Content: View>(
`let` value: Value?,
@ViewBuilder then modifySelfWithValue: (Self, Value) -> Content
) -> some View {
if let value = value { modifySelfWithValue(self, value) }
else { self }
}
}
็จๆณ๏ผ
// type: `Value?` `Value`
// โ โ
view.if(let: value) { (view, value) in
// modify the view with value (โญ๏ธ @ViewBuilder closure)
}
struct ContentView: View {
@State private var isNil = false
var value: Int? { isNil ? nil : 2 }
var body: some View {
VStack {
Color.red.overlay(Text("1"))
// โญ๏ธ view.if(let:then:)
.if(let: value) { (view, value) in
// construct `thisView` with `value`
VStack {
view
Color.orange.overlay(Text("\(value)"))
}
} // view modified by `ifLet`
.border(Color.blue, width: 3)
// toggles
Toggle(isOn: $isNil) { Text("value is nil") }
.padding()
.overlay(Rectangle().stroke(Color.gray, style: .init(dash: [6])))
} // VStack (container)
.padding()
.border(Color.gray, width: 3).frame(height: 300)
}
}
Swift โฉ Language Guide โฉ Generic Functions
Last updated