👔view.if(_:then:)

swiftcustomextensionView+.if(_:then:)

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

Was this helpful?