[英]Pass by reference primitive types in Swift
I am trying to have a model which shares a value with the objects it contains.我正在尝试建立一个模型,该模型与其包含的对象共享一个值。 In the below example I have a Model
object, a, which contains a Struct
, b.在下面的示例中,我有一个Model
对象 a,其中包含一个Struct
,b。 I would like them both to have access to a Bool
which is referenced by variables a and aa.我希望他们都能访问由变量 a 和 aa 引用的Bool
。 In order to do this, I have wrapped a Bool
in a Box
structure.为此,我在Box
结构中包装了一个Bool
。
struct Box<Value> {
var value:Value
}
struct Model {
var a: Box<Bool>
var b:B
struct B {
var aa:Box<Bool>
}
}
struct TestView : View {
@State var model:Model
var body: some View {
VStack {
Text(model.a.value.description)
Text(model.b.aa.value.description)
Button(action: {
self.model.a.value.toggle()
}) {
Text("Button")
}
}
}
}
However, when I run the code as such:但是,当我这样运行代码时:
let box = Box<Bool>(value: true)
let contentView = TestView(model: Model(a: box, b: Model.B(aa: box)))
The value in model.b.aa is not updated as I would expect. model.b.aa 中的值没有像我预期的那样更新。 Is there a different way I should be doing this?有没有不同的方式我应该这样做?
For your purpose, you'd need to wrap the primitive type in a class, and share an instance of that class.为了您的目的,您需要将原始类型包装在一个类中,并共享该类的一个实例。 There is no raw reference or pointer that can be shared between the structs.没有可以在结构之间共享的原始引用或指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.