# view\.if(\_:then:)

[swift](/ios/swift.md)⟩ [custom](/ios/custom.md) ⟩ [extension](/ios/custom/ext.md) ⟩ [View+](/ios/custom/ext/view.md) ⟩ <mark style="color:purple;">`.if(_:then:)`</mark>&#x20;

{% hint style="danger" %}
... there is yet <mark style="color:orange;">**another problem**</mark> beyond <mark style="color:red;">**animations**</mark>. When you use <mark style="color:purple;">`applyIf`</mark> with a view that contains a [＠State](/ios/swiftui/view/state/value/state.md) property, <mark style="color:red;">**all state will be lost**</mark> when the <mark style="color:orange;">**condition changes**</mark>. 👉 [objc.io](https://www.objc.io/blog/2021/08/24/conditional-view-modifiers/)
{% endhint %}

{% hint style="warning" %}
... the outermost type is a <mark style="color:purple;">**`_ConditionalContent`**</mark>. This is an <mark style="color:red;">**enum**</mark> that will *<mark style="color:orange;">**either**</mark>* contain the value from executing the <mark style="color:purple;">**`if`**</mark> branch, *<mark style="color:orange;">**or**</mark>* the value from executing the <mark style="color:purple;">**`else`**</mark> branch.  👉 [objc.io](https://www.objc.io/blog/2021/08/24/conditional-view-modifiers/)
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

````swift
extension View {
    /// transform self if `condition` is met.
    /// ```
    /// view.if(condition) { $0.hidden() }
    /// ```
    @ViewBuilder public func `if`<M: View>(
        _ condition: Bool, 
        then transform: (Self) -> M
    ) -> some View {
        if condition { transform(self) } 
        else { self }
    }
    
    /// transform self if `condition` is met, otherwise do another transform.
    /// ```
    /// view.if(condition) then: { $0.hidden() } else: { $0.border() }
    /// ```
    @ViewBuilder public func `if`<T: View, F: View>(
        _ condition: Bool, 
        then doThis: (Self) -> T, 
        else doThat: (Self) -> F
    ) -> some View {
        if condition { doThis(self) } 
        else { doThat(self) }
    }
}
````

{% endtab %}

{% tab title="💈  範例" %}

```swift
struct ContentView: View {
    
    let red  : Color? = .red
    let color: Color? = nil
    
    var body: some View {
        VStack {
            
            // .if()
            Text("Hello World")
                .if(true){ $0.padding() }
                .if(true){ $0.border(Color.black) }
                
            // .if(_:then:else:)
            Text("Hello World")
                // ⭐️ Swift 5.3: Multiple Trailing Closures
                // .if(true) { $0.padding() } else: { $0.background(Color.purple) }
                .if(false, then: { $0.padding() }, 
                    else: { $0.background(Color.purple) })
                
            // ⭐️ SwiftUI 新功能：目前沒作用！
            // .ifLet(_:then:)
            Text("Hello World")
                .ifLet(red) { $0.foregroundColor($1) }
            
        } // HStack
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.gray)
            .padding()
            .background(Color.orange)
    }
}
```

{% endtab %}

{% tab title="📗 參考" %}

* [x] Design+Code ⟩ [Conditional modifier](https://designcode.io/swiftui-handbook-conditional-modifier)
* [x] SwiftLee ⟩ [How to create a Conditional View Modifier in SwiftUI](https://www.avanderlee.com/swiftui/conditional-view-modifier/)
* [ ] [Conditional view modifiers](https://fivestars.blog/swiftui/conditional-modifiers.html) - Five Stars
* [x] objc.io ⟩ [Why Conditional View Modifiers are a Bad Idea](https://www.objc.io/blog/2021/08/24/conditional-view-modifiers/) ⭐️
* [ ] [新版 SwiftUI 的 ViewBuilder 可以輸入 if let，switch & 宣告變數常數](https://medium.com/彼得潘的-swift-ios-app-開發問題解答集/swiftui-的-viewbuilder-可以輸入-if-let-switch-了-48601cac88ba) - 彼得潘
* [ ] [\[Swift 5.3預覽\] Multiple Trailing Closures](https://medium.com/史努比的第一個家/swift-5-3預覽-multiple-trailing-closures-c6cdbeb1570e) - 史努比的第一個家
  {% endtab %}

{% tab title="📘 手冊" %}

* Swift ⟩ [Trailing Closures](https://docs.swift.org/swift-book/LanguageGuide/Closures.html#ID102)
  {% endtab %}

{% tab title="👥  相關" %}

* [🌀 View](/ios/swiftui/view/view/view.md) + [.hideIf(\_:)](/ios/swiftui/view/view/.hideif.md)
* Can we implement it with [ViewModifier](/ios/swiftui/view/modifier/viewmodifier.md)❓
* [view.if(let:then:)](/ios/custom/ext/view/.iflet.md)
* [ViewBuilder](/ios/swiftui/view/view-builder.md)
* Tips ⟩ [iOS version](/ios/appendix/tips/ios-version.md)
  {% endtab %}

{% tab title="⬇️ 應用" %}

* [view.overlayText()](/ios/custom/ext/view/view.overlaytext.md)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/custom/ext/view/.if.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
