๐ŸŒ€view.if(_:then:)

swiftโŸฉ custom โŸฉ extension โŸฉ View โŸฉ .if(_:then:)

... there is yet another problem beyond animations. When you use applyIf with a view that contains a ๏ผ State property, all state will be lost when the condition changes. ๐Ÿ‘‰ objc.io

... the outermost type is a _ConditionalContent. This is an enum that will either contain the value from executing the if branch, or the value from executing the else branch. ๐Ÿ‘‰ objc.io

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

Last updated