Swift协议和返回“ some View”的方法

时间:2020-08-03 01:00:00

标签: swift swiftui

因此,协议不支持some View作为返回类型...我正在尝试:

public extension View {
    func popSheet(isPresented: Binding<Bool>, arrowEdge: Edge = .bottom, content: @escaping () -> PopSheet) -> some View {
        Group {
            if UIDevice.current.userInterfaceIdiom == .pad {
                popover(isPresented: isPresented, attachmentAnchor: .rect(.bounds), arrowEdge: arrowEdge, content: {
                    content().popover()
                })
            } else {
                actionSheet(isPresented: isPresented, content: {
                    content().actionSheet()
                })
            }
        }
    }
}

protocol PopSheet {
    func actionSheet() -> ActionSheet
    associatedtype View
    func popover() -> View
}

但是整个函数声明都会失败,并且content().popover()错误也会出现。

Method must be declared internal because its parameter uses an internal type

Protocol 'PopSheet' can only be used as a generic constraint because it has Self or associated type requirements

Member 'popover' cannot be used on value of protocol type 'PopSheet'; use a generic constraint instead

2 个答案:

答案 0 :(得分:1)

这里根本没有错。只是几个小错误。

首先,您的View关联类型与SwiftUI.View无关。它恰好具有相同的名称。您可能是这个意思:

public protocol PopSheet {
    associatedtype V: View   // Create a new type that conforms to View
    func actionSheet() -> ActionSheet
    func popover() -> V
}

您的第二个问题是,由于PopSheet具有关联类型,因此您不能直接依赖它。您的意思是您期望某些符合PopSheet的具体类型:

func popSheet<Sheet: PopSheet>(isPresented: Binding<Bool>, 
                               arrowEdge: Edge = .bottom, 
                               content: @escaping () -> Sheet) -> some View {

这样,您的实现就可以了。

答案 1 :(得分:0)

对于const words = (w1, w2, w3) => { let ar = [w1, w2, w3] return ar.reduce((a, i) => i.length < a ? i.length : ar[0].length) } let output = words('hi', 'hello', 'good') console.log(output) // --> 2问题,原因是:

...

当我们尝试直接引用通用协议时会发生这种情况,即具有相关类型或要求符合类型(use a generic constraint instead所指)的协议。例如,内置的Self协议在其声明中使用Equatable

...

您可以在此great blog post中找到详细的说明。

美好的一天,祝您编程愉快!