You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中无法访问StepperIndicationType泛型枚举的custom case属性问题

问题:无法访问枚举关联值的属性

场景代码

不可修改的库枚举:

public enum StepperIndicationType<Content:View> {
    public typealias Width = CGFloat

    case circle(Color, Width)
    case image(Image, Width)
    case animation(NumberedCircleView)
    case custom(Content)
}

自定义View:

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

HostController中的@State数组:

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

尝试修改属性时出错:

indicators[3].name = "completed"

错误提示:Value of type StepperIndicationType has no member name


解答

问题原因

数组中的元素类型是StepperIndicationType<MyView>枚举实例,而非MyView。name是MyView的属性,而枚举的.custom case仅将MyView作为关联值存储,直接访问枚举实例的name自然找不到对应成员。

解决方法

方法1:直接通过枚举case判断修改

因为枚举和MyView都是值类型,需要先取出关联值、修改后重新生成枚举实例,再替换数组中的元素:

// 修改数组索引3的元素name
if case var .custom(targetView) = indicators[3] {
    targetView.name = "completed"
    indicators[3] = .custom(targetView)
}

方法2:给枚举扩展属性(更便捷)

虽然原枚举不可修改,但可以通过扩展添加可选的name属性,简化后续操作:

extension StepperIndicationType where Content == MyView {
    var name: String? {
        get {
            guard case .custom(let view) = self else { return nil }
            return view.name
        }
        set {
            guard case var .custom(view) = self, let newName = newValue else { return }
            view.name = newName
            self = .custom(view)
        }
    }
}

添加扩展后,就可以直接使用你最初的写法修改属性:

indicators[3].name = "completed"

内容的提问来源于stack exchange,提问作者Danil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 03:02:19