代码之家  ›  专栏  ›  技术社区  ›  Danil

无法访问通用下标

  •  0
  • Danil  · 技术社区  · 5 月前

    我在库中有这段代码,所以我无法修改它。

    public enum StepperIndicationType<Content:View> {
        public typealias Width = CGFloat
    
        case circle(Color, Width)
        case image(Image, Width)
        case animation(NumberedCircleView)
        case custom(Content)
    }
    

    我确实创建了StepperIndicatonType类型的实体 案例定制 并传递了属性视图 名称

    struct MyView: View {
        var name: String
        var body: some View {
           Image(name)
        }
    

    我确实在HostController中创建了这种类型的视图数组

    @State var indicators = [
    StepperIndicationType.custom(MyView(name: "pending")),
                             .custom(MyView(name: "pending")),
                             .custom(MyView(name: "pending")),
                             .custom(MyView(name: "pending"))]
    

    然后,我试图访问索引处的值,将属性名称更改为不同的图像,但我收到了一条消息 类型值阶跃指示类型< MyView >没有成员名称

    indicators[3].name = "completed"
    

    Xcode向我展示了我的类型,如下所示:

    let obj = indicators[3]
    

    [选项点击obj显示此类型]:

    StepperIndicationType<MyView>
    

    我很难弄清楚我做错了什么,以及为什么我无法访问数组索引处对象的属性

    1 回复  |  直到 5 月前
        1
  •  1
  •   Sweeper    5 月前

    只需使用a [String] :

    @State var indicators = ["pending", "pending", "pending", "pending"]
    

    这使得更新数组变得容易:

    indicators[3] = "completed"
    

    仅将数组转换为 [StepperIndicationType<MyView>] 在最后一刻。

    StepperView()
        // ...
        .indicators(indicators.map { .custom(MyView(name: $0)) })
        // ...
    

    或者,您可以添加 name 财产 StepperIndicationType 在扩展中,尽管我觉得这很丑陋。

    extension StepperIndicationType<MyView> {
        var name: String? {
            get {
                if case let .custom(content) = self {
                    content.name
                } else {
                    nil
                }
            }
            set {
                if case var .custom(content) = self, let newValue {
                    content.name = newValue
                    self = .custom(content)
                }
            }
        }
    }
    

    那么 indicators[3].name = "completed" 将编译。