Swift协议和返回“的方法”;“一些观点”;
因此,协议不支持将Swift协议和返回“的方法”;“一些观点”;,swift,swiftui,Swift,Swiftui,因此,协议不支持将某些视图作为返回类型。。。我正在尝试这个: public extension View { func popSheet(isPresented: Binding<Bool>, arrowEdge: Edge = .bottom, content: @escaping () -> PopSheet) -> some View { Group { if UIDevice.current.userInterfac
某些视图
作为返回类型。。。我正在尝试这个:
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
}
公共扩展视图{
func popSheet(显示:绑定,箭头边:边=.bottom,内容:@escaping()->popSheet)->一些视图{
团体{
如果UIDevice.current.userInterfaceIdiom==.pad{
popover(isPresented:isPresented,attachmentAnchor:.rect(.bounds),arrowEdge:arrowEdge,内容:{
content().popover()
})
}否则{
操作表(显示:显示,内容:{
content().actionSheet()
})
}
}
}
}
协议PopSheet{
func actionSheet()->actionSheet
关联类型视图
func popover()->视图
}
但是整个函数声明失败,content().popover()
也会出错
方法必须声明为内部,因为其参数使用内部类型
协议“PopSheet”只能用作一般约束,因为它具有自身或关联的类型要求
成员“popover”不能用于协议类型“PopSheet”的值;使用通用约束代替
对于使用通用约束代替
问题,原因是:
当我们试图直接引用一个通用协议时,就会发生这种情况,也就是说,一个协议要么有关联的类型,要么需要已知一致性类型(SelfSelf
引用)。例如,内置的equalable
协议在其声明中使用Self
你可以在这篇文章中找到详细的解释
美好的一天,快乐的编码 这里根本没有什么问题。只是几个小错误 首先,您的
视图
关联类型与SwiftUI.View
无关。它只是碰巧有相同的名字。你可能的意思是:
public protocol PopSheet {
associatedtype V: View // Create a new type that conforms to View
func actionSheet() -> ActionSheet
func popover() -> V
}
第二个问题是您不能直接依赖PopSheet,因为它有一个associatedtype。您的意思是,您希望某个具体类型符合PopSheet:
func popSheet<Sheet: PopSheet>(isPresented: Binding<Bool>,
arrowEdge: Edge = .bottom,
content: @escaping () -> Sheet) -> some View {
func-popSheet(显示:绑定、,
箭头边:边=.bottom,
内容:@escaping()->Sheet->一些视图{
这样,您的实现应该很好。这个固定错误2和3,但我仍然得到一个与第一个
实例方法类似的错误,必须声明为内部,因为它的泛型参数使用内部类型。这是因为扩展名标记为public
,但不是PopSheet。在我的回答中,我将public
添加到爆米花。