Swift Array Pass by Value...same memory address? - ios

Can someone please clear this up for me.
I understand (thought) Swift passes arrays by value as it is a struct.
But when I pass an array via segue to the next view controller it appears to me that it is passing by reference, as when I check the memory address of the array they are the same.
This is how I'm checking
println("\(unsafeAddressOf(runs))") // 0x0000000174240c00
I would have thought these memory addresses would be different ? Or am I just confusing myself.
The Run / StaffTask classes both inherit from NSObject for saving purposes.
class Run: NSObject, NSCoding { }
Furthermore, if I access a item in the array
var service = self.staffTasks[indexPath.row]
and edit the value, both the service variable value and the element in the array are updated. They have the same memory address, as shown by
println("\(unsafeAddressOf(service)) \(unsafeAddressOf(self.staffTasks[indexPath.row]))")
Also...
staffTasks are a subset of a larger array called runs
When I search for the service object, with the larger set, I find that they are also the same memory address
if let index = find(self.runs, self.staff) {
println("local \(unsafeAddressOf(self.staff)) main list \(unsafeAddressOf(self.runs[index]))")
}
I am using NSCoding to save my objects, so I thought I would need to find the service object within the larger set, replace that object and then save them out.
But turns out I don't need to, I am able to edit the service variable and array of runs is updated on automatically ... like a reference type would be.
Passing? .. setting the Var
in prepare for segue, just setting the local var in the second VC using the standard way, var runsInSecondVC = runs. Not using, &pointers or any other weirdness.
Thanks for any help.
Class Basic Details
class Run: NSObject, NSCoding {
var runDate:NSDate!
var staffName:String!
var staffEmail:String!
var runTasks:[StaffTask]!
}
class StaffTask: NSObject, NSCoding {
var taskName:String
var taskTime:NSInteger
var clientName:String!
}
These are the basic of these classes. Nothing complicated.

passes arrays by value
No. Swift arrays are a value type. This does not mean they are pass-by-value. It means that you can mutate an array by way of a reference without affecting other references to which that array has been assigned.

You are getting a little confused about the array itself and the contents of the array.
..if I access a item in the array
var service = self.staffTasks[indexPath.row]
and edit the value, both the service variable value and the element in the array are updated. They have the same memory address...
Putting an object into an array doesn't copy the object. In fact, the array holds a reference to the object, so the line above actually says "make a variable, service that holds a reference to the object that self.staffTasks[indexPath.row] holds a reference to". There is only one object, now referred to in two places, so when you update the object that change is visible through both variables.

Related

Should I use var or let for an object later mutated?

I have an iOS app that, upon startup, loads objects from persistent storage that will be manipulated later in the app. For example, on startup it loads patient profiles in an array. Does it matter if I define the items I add to the array as variables, versus constants, if they will be modified by the app later (say in a different View Controller)?
In my App Delegate, I load them like this:
func loadProfiles() {
var profileRecord: COpaquePointer = nil
if sqlite3_prepare_v2(db, "SELECT profilesid, objectSyncStatus, profileName, profileRelationship, profileFName, profileLName, profileAddress, profileCity, profileState, profileZip FROM profiles", -1, &profileRecord, nil) == SQLITE_OK {
if sqlite3_step(profileRecord) == SQLITE_ROW {
// Load profile stubs for each person
var newProfile = DBProfile(withDatabase: db, fromRecord: profileRecord, withLanguage: appLanguage, loadAllData: false)
patientProfiles.append(newProfile)
}
}
}
Of course, I get a warning that newProfile is not mutated, and it wants to change it to let newProfile = ... before it is added to the array. But, if I do that, will it become immutable later?
Thanks for the answers.
The compiler is actually really good at determining whether you should use let or var, and in this case, it is correct.
var should be used anywhere the data will be mutated. For example:
A struct value where the properties will be mutated
Pointers (like your COpaquePointer)
Instances of classes that will be reassigned to different class instances
let should be used anywhere the data will not be mutated. For example:
Constants
Values to be added to arrays, dictionaries, arguments to functions, etc.
Class instances where the instance will not be reassigned.
Note that for instances of classes, you can still modify the properties of the class even if it is defined as let. var should only be used in this case when the class itself will be reassigned.
In the case of your newProfile variable, during it's lifetime it is never mutated. The object is created, then immediately appended to your array. That array needs to be defined with var because it is mutated with that append, but newProfile never gets changed. You can change the value that was appended from newProfile through the array at a later date if you'd like because the patientProfiles array is mutable.
A good practice for when you are not sure whether to use let or var is to start with let and see if the compiler complains. If it does, then change it to var.
I see that you do not quite understand what is constant and how it works with value and reference types.
You can think of constant as glass box with lock and key.
Once you put something in box and lock it you threw away the key so you can see box contents (read properties and call non-mutating methods) but can not change it.
Words mutated and immutable can be only applied to value types because in case of value type the box holds value itself and if some method of value can change value then it must be marked with keyword mutating so it will not be visible through box glass.
In case of reference type the box holds reference to instance of type. If you define constant of reference type then you have box with reference. You can not change the reference, but you can read it and then go and find instance by that reference and do whatever you like with that instance.
In your case you define constant:
let newProfile = DBProfile(...)
and DBProfile is class (reference type).
You can not assign another reference to newProfile but you do whatever you like with object that referenced by newProfile. So you append it to patientProfiles array and you can get it later from this array and do what you want.

What the difference when declaring these variables in swift using ! or ()

What is the difference of declaring variables this way?
var contacts: [Person]!
var contacts = [Person]()
By using var contacts: [Person]! you don't actually initialize a Person array.
var contacts: [Person]! // contacts still nil
var contacts = [Person]() // Person array with 0 objects
If you use () instead you initialize an empty Person array.
Variable declarations in Swift take the following form:
var name: Type = initialValue
That is, you declare a variable called name of some Type, and set it to an initialValue.
There are many shorthand forms though, so you will see various alternatives. The one you see the most often is leaving off the Type part. If you do, then the type of name is “inferred” from the initialValue.
This is what is happening with var contacts = [Person](). The type is an Array of Person. The () is calling the initializer (i.e. creating the array).
Alternatively, you can declare a variable, with a type, but not give it an initial value. But the compiler won’t let you use it until you are guaranteed to have set it with an initial value. So for example, you could write var contacts: [Person], then later contacts = [Person]().
When you write var contacts: [Person]!, with a !, you are declaring a variable of type Optional<[Person]> – that is, a type that can either be nil, or contain an array. Unlike regular arrays, optionals of arrays have a default value if you don’t initialize them. The default value is nil – that is, that the optional does not contain an array.
But the ! (instead of the more common ?) means it is declared to be a special kind of optional, called an “implicitly-unwrapped optional” – that is, an optional that, when you use it in certain ways, will act as if it isn’t optional. The big downside of this is that it will let you use it as if it isn’t an optional. But if you do and it is nil then your program will crash. So before anyone uses contacts, it will need to be initialized (such as with contacts = [Person]() or assigning some existing array to it)
For this reason, it’s best to not use these implicitly-unwrapped optionals except in very specific circumstances. They sometimes seem like they’re convenient but they’re usually not the best option as they’re dangerous.
The operator : is not declaring, its just saying which type a variable is
Operator = is as in every other language a declaring operator which in this case followed by the () which in this case declared a new array of Person.
Other people provided the differences, I'll give you the scenarios of when either should be used.
var contacts: [Person]! //implicitly unwrapped optional. #1
var contacts = [Person]() //array initialization. #2
I use #1 when I create a variable that won't be initialized by it's own class. This situation occurs when I implement a detail view that takes in information that is passed by another controller.
For #2, use when you want to initialized a new empty array.

Simple Clarification Objects Swift Language

I have a very simple question on something that I may have misunderstood.
I have two UIViews "A" and "B". If I write :
let A = UIView() // Or something else
let B = A
and then I change properties of B (for exemple the frame), will the properties of A change too ?
I though not, but I was animating a view, so I had the initial view and the final view. I created a transition view like this :
let transitionView = finalView
and then I changed the properties of transitionView, the position of a label for exemple.
When I added the final view at the end of the animation, the label was at the new position.
Why ? Thanks
In swift types are split in 2 main categories:
reference types
value types
Classes are reference types; structs (which include arrays and dictionaries), basic data types (int, float, string, etc.), and enums are all value types.
A value type is always passed by value, which means when assigning to a variable or passing to a function/method, a copy of the original data is created. There's an exception to this rule: a function/method can use the inout modifier on a value type parameter to have it passed by reference.
Note that the compiler and the runtime usually do optimizations, so a copy is not always created unless strictly needed - what's important is that we, as developer, know that we are working on a copy and not on the original data.
A reference type is always passed by reference, which means when assigning it to a variable or passing it to a function/method, a reference to the data and not the data itself is assigned/passed.
UIView is a class, so when you create an instance, assign it to a variable, then assign that variable to another variable, the reference to the instance and not the instance itself is assigned. Both variables point to the same UIView instance. Any change made to the instance is visible to all variables referencing that instance.
Suggested reading: Classes and Structures
Because B and A are not two views. They are references to the same UIView object.
That, in turn, is because class instances are passed as reference types in Swift.
See now my little essay on this topic here: https://stackoverflow.com/a/27366050/341994

How to build an array in swift re-using a variable

I plan to use a class object variable to capture user entered data sets in recurring cycles and when a data set is complete add this to an array holding all these class variables.
Simple example code in playground:
class Example {
var a = 1
var b = 5
}
var exArray = [Example] () // this is the array holding the class variables
var anExample = Example () // default-init the "re-usable" variable
exArray.append(anExample)
exArray[0].a // results in 1 as expected
exArray[0].b // results in 5 as expected
exArray.count // 1 as expected
// now changing the re-usable variable properties with new user entered data
anExample.a = 3
anExample.b = 7
// appending the altered variable
exArray.append(anExample)
exArray[0].a // shows 3 where I still expect 1
exArray[0].b // shows 7 where I expect 7
exArray.count // shows 2 as expected
it seems the array holds the variable itself (pointer?) not a copy of the variable, so this keeps changing within the array. Any ideas how I can "reset" the class variable without changing the array member?
If you create an instance of a class and assign to a variable, the variable contains a reference to the instance and not the instance itself.
When you add the variable to the array, you add the reference to the class instance. If you later change the instance properties and add to the array, you add the same reference as you added before. Result: all of what you insert into the array is a variable containing a reference to the same class instance.
Depending on your app architecture and logic, you might want to turn the class into a struct - differently from a class, which is a reference type, the struct is a value type, so when moved around, a copy of it is created. That happens when:
you assign the variable to another variable
you pass it to a function or method (unless the inout modifier is used)
As a direct consequence, if you insert a struct instance into an array, you call a method, so a copy of the struct is created and inserted into the array - that copy has no relationship with the original struct, besides having the same values at the moment it is copied. So any change you do to any of them, it is not reflected to the other.
If you want your data copied when you assign it, you can define Example as a struct instead of a class See this answer for the difference between struct and class
struct Example {
var a = 1
var b = 5
}
Now when you assign it to the array, it will add a copy to the array with the data at the point where you assigned it.
But if you want to keep using a class you should create a new instance with the data you want before you append it to the array.

Passing Arrays/Objects between ViewControllers in Swift

Following on from this question: Is there a reason that Swift array assignment is inconsistent (neither a reference nor a deep copy)? -
I have been playing with passing objects in Swift and noticed some strange results.
To clarify the kind of behaviour i'm used to (prior to Swift) would be that of Objective C.
To give an example in one of my Applications (written in Obj C) I have the concept of a 'notification list'. - really just an array of custom objects.
In that App I often pass my global array of 'notifications' to various viewControllers which provide a UI to update the list.
When I pass the global array to a child viewController I assign it to a local array variable in the recipient object. Then, simply by updating/changing the local array these changes are reflected in the global array on the rootViewController. I understand this behaviour is implicit in Objective C as objects as passed by reference, but this is really handy and I have been trying to replicate this behaviour in Swift.
However whilst I have been rewriting my App in Swift I've hit a wall.
I first tried to pass a Swift array of strings (not NSMutableArray) from the rootViewController to a child viewController (as described above).
Here is the behaviour when passing in the array of Strings the child viewController:
I Pass in:
[Bill, Bob, Jack] and then assign this passed array to a local array for local modification,
Then I append the String “Frank” to the local array
The results are:
Local array = [Bill, Bob, Jack, Frank]
Global array = [Bill, Bob, Jack]
No changes to the local array are reflected back to the global array. - The SAME result occurs for a change of element (without changing the length of the array.)
I have also tried the above experiment with a more real world example - passing in an array of my custom 'notification' objects to a child viewController. The SAME result occurs with none of the changes to the locally assigned array of custom objects being reflected to the original global array that was passed in.
This behaviour is not desirable to me, I assume the best practice here is to use delegate protocols to pass the modified array (or whatever object) back to the parent object and then to manually update the global array?? - if so this creates quite an extra workload over the Objective C style behaviour.
Finally I did try the inout keyword, which effectively lets you directly modify the function parameter var thats passed to the destination object.
Changes are reflected back to the global array (or object) However the problem is, if the input parameter is assigned to a local variable (to edit outside of scope of the init function) changes to the local variable are still not reflected in global scope.
I hope the above makes sense - It's really stifling my productivity with Swift.
Am I missing something or is this schizophrenic behaviour expected?
If so what is best practice on passing modified data back, delegates?
The linked question provides the answer - it is for performance.
The behaviour may not be desirable for you, but I would say that relying on side-effects from calling methods to modify parameters is the behaviour that is not considered desirable - particularly in a multi-threaded, multi-core environment where data structures can be corrupted.
A design that relies on side-effects is flawed, in my opinion.
If functions need to modify the "global" then they should either return the new value, or if that isn't possible then you should wrap your array inside an object and provide appropriate functions to manipulate the data values.
Swift blurs the lines between intrinsic and object somewhat with arrays, which makes it a little confusing - in Objective-C an NSMutableArray is an object so it always passed by reference.
For notifying other objects that the data has changed you can use an observer pattern. The typical delegate pattern only has a single registered delegate - With an observer pattern you can have multiple registered observers.
You can do this through NSNotificationCenter or an array of "delegates". The former has the advantage of decoupling the code more than delegation
Why don't you create a Model class that contains the array as a var. Add methods to the Model class to manipulate the array and store the new instance in the property. Create a single instance of the Model class at startup and pass it to the view controllers. They all access the array through the Model or through methods in the Model class. The behavior of Swift (where it copies the array on change of size) will be hidden from all of the view controllers.

Resources