How to set default clouse param in View method?

六眼飞鱼酱① 提交于 2021-02-10 06:18:28

问题


I tried to set else default param in ifLet method but I face an error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements. What did wrong?

extension View {
    func ifLet<Value, Then: View, Else: View>(
        _ value: Value?,
        then: (Value) -> Then,
        else: () -> View = { EmptyView() }
    ) -> _ConditionalContent<Then, Else> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: `else`())
        }
    }
}

Using:

struct TestView: View {
    var test: String?

    var body: some View {
        Group {
            ifLet(test) { Text($0) }
            ifLet(test, then: { Text($0) }, else: { Text("Empty") })
        }
    }
}

The best solution without using the unofficial _ConditionalContent that might be changed or removed in the future check out here


回答1:


Here is possible approach. Tested & works with Xcode 11.2 / iOS 13.2.

struct TestingIfLet: View {
    var some: String?
    var body: some View {
        VStack {
            ifLet(some, then: {value in Text("Test1 \(value)") })
            ifLet(some, then: {value in Text("Test2 \(value)") }, 
                else: { Text("Test3") })
        }
    }
}

extension View {

    func ifLet<Value, Then: View>(
        _ value: Value?,
        then: (Value) -> Then
    ) -> _ConditionalContent<Then, EmptyView> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: EmptyView())
        }
    }

    func ifLet<Value, Then: View, Else: View>(
        _ value: Value?,
        then: (Value) -> Then,
        else: () -> Else
    ) -> _ConditionalContent<Then, Else> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: `else`())
        }
    }
}


来源:https://stackoverflow.com/questions/60223711/how-to-set-default-clouse-param-in-view-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!