如果这个问题有点抽象,我们深表歉意,但现在是:
API返回一个由几个简单字段组成的资源列表。其中一个字段(示例中的"view-id"(告诉客户端在渲染数据时使用哪个SwiftUIView
。
[
{
"title": "Example Title"
"image": "https://www.example.com/some/image.png"
"view-id": "text-row" // tells the client to use, say, `TextRowView`
},
{
"title": "A Second Title"
"image": "https://www.example.com/some/other/image.png"
"view-id": "image-row" // tells the client to use, say, `ImageRowView`
}
]
我的目标是找到一种可扩展的方法,允许在运行时基于API中的view-id
选择View
类型。
在我试图解决这个问题的过程中,我定义了以下协议来描述一种可以创建视图的类型
protocol MyViewBuilder {
associatedtype Content: View
func buildView(data: Data) -> Content
}
/// concrete implementation of a `MyViewBuilder`
struct MyExampleViewBuilder {
func buildView(data: Data) -> Text {
Text(data.string)
}
}
我定义了以下协议来将"view-id"从API映射到特定类型的视图:
protocol MyViewDescriptor {
associatedtype Content: View
var id: String { get }
}
/// concrete implementation for a `MyViewDescriptor`
struct MyExampleDescriptor {
associatedtype Content: Text
var id: String = "text-row"
}
现在,我构建了一个允许注册&访问这些片段如下:
class MyGlueCode: MyViewBuilder {
func register<D, B>(_ descriptor: D, viewBuilder: B) where D: MyViewDescriptor,
B: MyViewBuilder,
D.Content == B.Content {...}
func buildView<D, Content>(descriptor: D, data: Data) -> Content where D: MyViewDescriptor, Content == D.Content { ... }
}
现在,上面的代码可以通过一点类型擦除来工作,但我正在努力的是如何为buildView(descriptor:data:)
保留/生成"descriptor"参数。但我无法设计一种方法在呼叫站点直接实现这一点,理想情况下,我可以在那里做一些简单的事情,比如
ForEach(data) {
SomeClass().view(for: $0)
}
我被卡住了:(救命!
这是一种可能的方法。使用Xcode 11.4/iOS 13.4 进行测试
enum ViewType: String {
case text = "text-row"
case image = "image-row"
static func view(for data: Data) -> some View {
let type = Self(rawValue: data.viewId)
return Group {
if type == nil {
Text("Unsupported View Type")
} else if type == .text {
TexDataView(data: data)
} else if type == .image {
ImageDataView(data: data)
}
}
}
}
struct DemoDataView: View {
let data: Data
var body: some View {
ViewType.view(for: data)
}
}
假设复制
struct Data {
let title: String
let image: String
let viewId: String
}