是否可以将@Published 映射到@Binding?

Is it possible to map @Published to @Binding?

我有以下代码:

final class State: ObservableObject {
    @Published var isSelected = false
    @Published var selectedColor: Color = .white
}

private enum Constants {
    static let colors: [Color] = [.black, .white, .blue, .green, .yellow, .red]
}

var body: some View {
    VStack(spacing: Constants.spacing) {
        HStack {
            Eraser()

            ForEach(Constants.colors, id: \.self) { color in
                PaintColor(color: color, isSelected:  $state.isSelected)
                    .frame(maxWidth: .infinity)
            }
        }
        .padding(Constants.colorsInsets)
    }
    .background(Constants.backgroundColor)
}

我实际上想做的是根据 selectedColor 的值将 PaintColor 上的 isSelected 设置为 truefalse。可以map一个@Published属性吗?我想做类似的事情:

PaintColor(color: color, isSelected: state.selectedColor == color)

可以使用可计算的绑定,例如

PaintColor(color: color, isSelected:  Binding(
   get: { state.selectedColor == color },
   set: { state.selectedColor = [=10=] ? color : .white }
))
.frame(maxWidth: .infinity)

*实际上,如果可能全部未选中,则需要将 selectedColor 设为可选(然后重置为 nil 而不是上面的 .white

@Published var selectedColor: Color? = .white