我的数据模型:
class MyData: ObservableObject {
@Published var aabbData = [AabbData]()
}
struct AbData: AabbData{
var x = 0
}
protocol AabbData{
}
在我的视图代码中,我想将 aabbData 的元素向下转换为 AbData 类型,并将其 x 属性绑定到控件的值。所以我尝试编写代码:
@EnvironmentObject var data: MyData
let index = 0
//some other code
//method 1
Slider(value: ($data.aabbData[index] as! Binding<AbData>).x, in: -100...100, step: 1)
//error: Cast from 'Binding<AabbData>' to unrelated type 'Binding<AbData>' always fails
//method 2
Slider(value: Binding<Int>(
get:{
(data.aabbData[index] as! AbData).x
},
set:{
(data.aabbData[index] as! AbData).x = $0
//error: Cannot assign to immutable expression of type 'Int'
}
), in: -100...100, step: 1)
代码不起作用。如何将向下转换值的属性绑定到控件的值?