gpt4 book ai didi

swiftui - 如何在 SwiftUI 中实现像 AnyView 这样的类型删除结构?

转载 作者:行者123 更新时间:2023-12-04 12:56:42 26 4
gpt4 key购买 nike

我很好奇 AnyView 的默认实现在 SwiftUI 中。如何将具有不同泛型类型的结构放入协议(protocol)数组中?

例如:

let a = AnyView(Text("hello"))
let b = AnyView(Image(systemName: "1.circle"))
let genericViews = [a, b] // No compile error

而我的实现:
struct TypeErasedView<V: View>: View {
private var _view: V
init(_ view: V) {
_view = view
}
var body: V {
_view
}
}

let a = TypeErasedView(Text("Hello"))
let b = TypeErasedView(Image(systemName: "1.circle"))
let genericViews = [a, b] // compile error


编译错误将是“只能将异构集合文字推断为'[Any]';如果这是有意的,请添加显式类型注释”。

有没有人有任何想法?

最佳答案

这是一个可能的方法的演示。它被简化了,但显示了如何做到这一点的一般想法……或者至少是一个方向。

完整的可编译和工作模块。在 Xcode 11.2/iOS 13.2 上测试

import SwiftUI

private protocol TypeErasing {
var view: Any { get }
}

private struct TypeEraser<V: View>: TypeErasing {
let orinal: V
var view: Any {
return self.orinal
}
}

public struct MyAnyView : View {
public var body: Never {
get {
fatalError("Unsupported - don't call this")
}
}

private var eraser: TypeErasing
public init<V>(_ view: V) where V : View {
eraser = TypeEraser(orinal: view)
}

fileprivate var wrappedView: Any { // << they might have here something specific
eraser.view
}

public typealias Body = Never
}


struct DemoAnyView: View {
let container: [MyAnyView]
init() {
let a = MyAnyView(Text("Hello"))
let b = MyAnyView(Image(systemName: "1.circle"))
container = [a, b]
}

var body: some View {
VStack {
// dynamically restoring types is different question and might be
// dependent on Apple's internal implementation, but here is
// just a demo that it works
container[0].wrappedView as! Text
container[1].wrappedView as! Image
}
}
}

struct DemoAnyView_Previews: PreviewProvider {
static var previews: some View {
DemoAnyView()
}
}

关于swiftui - 如何在 SwiftUI 中实现像 AnyView 这样的类型删除结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com