如何在 View 方法中设置默认的 clouse 参数? [英] How to set default clouse param in View method?

查看:40
本文介绍了如何在 View 方法中设置默认的 clouse 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 ifLet 方法中设置 else 默认参数,但我面临一个错误:Protocol 'View' 只能用作通用约束,因为它有自己或相关的类型要求.做错了什么?

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

使用:

struct TestView: View {
    var test: String?

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

不使用非官方 _ConditionalContent(将来可能会更改或删除)的最佳解决方案请查看 这里

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

推荐答案

这是可能的方法.测试&适用于 Xcode 11.2/iOS 13.2.

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

这篇关于如何在 View 方法中设置默认的 clouse 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆