Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to assign a variable by reference, not by value?

Tags:

swift

I'm trying to get a reference to an Array and make modifications to it. Because Arrays in Swift are value types, instead of reference types, if I assign my array to a variable first, I am getting a copy of the array instead of the actual array:

var odds = ["1", "3", "5"]
var evens = ["2", "4", "6"]

var source = odds
var destination = evens

var one = odds.first!

source.removeFirst() // only removes the first element of the `source` array, not the `odds` array

destination.append(one)

When we look at the odds and evens arrays, they are unaltered because we changed the source and destination arrays.

I know that I can use the inout parameter attribute on a function to pass them by reference, instead of by value:

func move(inout source: [String], inout destination: [String], value:String) {
    source.removeAtIndex(source.indexOf(value)!)
    destination.append(value)
}

move(&odds, destination: &evens, value:one)

Is there a way to assign these arrays to a variable by reference, instead of by value?

like image 803
Wayne Hartman Avatar asked Jul 21 '16 14:07

Wayne Hartman


People also ask

How do you pass a variable as a reference in Swift?

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 (&).

How do you assign a reference to a variable?

To assign reference to a variable, use the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare the reference parameters using the ref keyword.

Is Swift pass by value or pass by reference by default?

it is Pass By Value. Pass By Reference Classes Always Use Pass by reference in which only address of occupied memory is copied, when we change similarly as in struct change the value of B , Both A & B is changed because of reference is copied,.

Is Swift value by reference?

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 .


1 Answers

You cannot assign an array to a variable by reference in Swift.

"In Swift, Array, String, and Dictionary are all value types..."

Source: https://developer.apple.com/swift/blog/?id=10

like image 83
Jake Farley Avatar answered Oct 16 '22 10:10

Jake Farley