【问题标题】:Is it possible to fulfil the generic constraint on a Swift (SwiftUI) class in a new init?是否可以在新的 init 中实现对 Swift (SwiftUI) 类的通用约束?
【发布时间】:2021-03-29 00:39:15
【问题描述】:

虽然下面的例子很简单,但它无法编译,因为 Swift 无法确定 Text() 视图是泛型约束所需的内容类型(错误“无法将'Text'类型的值转换为闭包结果类型'内容'")。

有什么办法可以让 init 满足通用约束?

extension VStack {
    init() {
        self.init(spacing: 0) {
            Text("Test")
        }
    } 
}

用 George_E 的回复更新后的完整示例如下所示。

extension VStack {
    init<InnerContent: View>(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, @ViewBuilder content: @escaping (GeometryProxy) -> InnerContent) where Content == GeometryReader<InnerContent> {
        self.init(alignment: alignment, spacing: spacing) {
            GeometryReader { proxy in
                content(proxy)
            }
        }
    }
}

【问题讨论】:

    标签: swift generics swiftui


    【解决方案1】:

    您可以在 init 中包含 where 子句:

    extension VStack {
        init() where Content == Text {
            self.init(spacing: 0) {
                Text("Test")
            }
        }
    }
    

    或者:

    extension VStack where Content == Text {
        init() {
            self.init(spacing: 0) {
                Text("Test")
            }
        }
    }
    

    【讨论】:

    • 啊哈!杰出的!你答案的第一部分太棒了!我希望我能给你更多的支持!
    猜你喜欢
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多