简体   繁体   中英

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. I would like them both to have access to a Bool which is referenced by variables a and aa. In order to do this, I have wrapped a Bool in a Box structure.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM