I've looked to similar questions but I haven't seen an answer that I am satisfied with.
Is it possible or advisable to pass structs by reference? If so how?
Here is a code as a reference for examples:
struct MyData { var contentId: Int = 0 var authorId: Int = 0 var image: UIImage = UIImage(named: "myimage") }
As you see my main reason of doing this is because not having my image multiplying all over the place.
In Swift, instances of classes are passed by reference. This is similar to how classes are implemented in Ruby and Objective-C. It implies that an instance of a class can have several owners that share a copy. Instances of structures and enumerations are passed by value.
In Swift there are two categories of types: value types and reference types. A value type instance keeps a unique copy of its data, for example, a struct or an enum . A reference type, shares a single copy of its data, and the type is usually a class .
Structs can be passed by reference using the inout keyword and the & operator. This practice is discouraged unless you can prove it's the only way to get the performance you need in a critical situation. Note that you won't save the burden of copying the UIImage by doing this.
To pass parameter by reference to a Swift function, define this parameter with inout keyword, and use preface the parameter in function call with ampersand (&).
Structs can be passed by reference using the inout
keyword and the &
operator.
struct Test { var val1:Int let val2:String init(v1: Int, v2: String) { val1 = v1 val2 = v2 } } var myTest = Test(v1: 42, v2: "fred") func change(test: inout Test) { // you can mutate "var" members of the struct test.val1 = 24 // or replace the struct entirely test = Test(v1: 10, v2: "joe") } change(test: &myTest) myTest // shows val1=10, val2=joe in the playground
This practice is discouraged unless you can prove it's the only way to get the performance you need in a critical situation.
Note that you won't save the burden of copying the UIImage by doing this. When you put a reference type as a member of a struct, you still only copy the reference when you pass it by value. You are not copying the contents of the image.
Another important thing to know about struct performance is copy-on-write. Many built in types like Array are value types, and yet they're very performant. When you pass around a struct in Swift, you don't undergo the burden of copying it until you mutate it.
Check out the WWDC video on value types to learn more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With