for anItem in jsonResult as! [Dictionary<string, anyobject="">] {
var deliveryCustomer:deliveryCustomers = deliveryCustomers()
if let idString = (anItem["id"]) as? NSString {
deliveryCustomer.id = idString
}
if let firstNameString = (anItem["firstName"]) as? NSString {
deliveryCustomer.firstName = firstNameString
}
}
Line 2, you create the object.
Line 5, you do not change the object reference, you just change one of its properties.
Hence, the object itself is unchanged.
So, you can replace var with let.
If that can help you, imagine you have a
class Person {
private var name: String // Make it private, so that it cannot be changed from outside
private var firstName: String
var age: Int
init(name: String, firstName: String, age: Int) {
self.name = name
self.firstName = firstName
self.age = age
}
}
let someGenius = Person(name: "Einstein", firstName: "Albert", age: 80)
someGenius.age = 85
someGenius.name = "Other" // Error 'name' is inaccessible due to 'private' protection level
someGenius points to a person that will not change. To make it sure, the name and firstName are declared as private.
But the age can change, of course. That does not change the person, it is still Albert Einstein !
That would be different, if you declared a struct and not a class:
You get an error with a let declaration
struct Personnage {
var name: String // Make it private, so that it cannot be changed from outside
var firstName: String
var age: Int
init(name: String, firstName: String, age: Int) {
self.name = name
self.firstName = firstName
self.age = age
}
}
let someOne = Personnage(name: "Einstein", firstName: "Albert", age: 80)
someOne.age = 85 // Cannot assign to property: 'someOne' is a 'let' constant
The core reason is that
- class are reference objects; instance is a reference to the object ; changing the content does not change the instance value
- struct are value objects: instance is the content ; changing the content does change the instance value.
« Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference. »
Extrait de: Apple Inc. « The Swift Programming Language (Swift 4). » Apple Books.