Wednesday, December 27, 2023
HomeiOS Developmentios - Swift structs are immutable, so how come I can change...

ios – Swift structs are immutable, so how come I can change them?


Structs aren’t immutable. Nevertheless, what they’re one thing referred to as worth sorts which suggests they’ve implicit copying when handed to capabilities. When you move a struct to a perform and carry out an motion on the struct contained in the perform that mutates it, the outer model of the struct stays unchanged for the reason that one handed to the perform was in truth a duplicate.

Contemplate the next:

struct Foo {
    var worth: Int
}

func bar(_ f: Foo) {
    f.worth += 1
}

var f = Foo(worth: 1)
bar(f)
// f.worth remains to be 1

In an effort to mutate a struct inside a perform you could explicitly move it as inout:

func baz(_ f: inout Foo) {
    f.worth += 1
}

baz(&f)
// f.worth is now 2

Edit: notice that I have not used Swift UI and I do not actually know the way the behaviour of structs applies to that exact framework. This reply is about structs in Swift within the normal sense.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments