0

I am coming from C++ and learning Swift now and I have some problems to understand the Swift const concept. This code is from a IOS development book and I have problems to understand why this is working.

    let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150)
    let firstView = UIView(frame: firstFrame)
    firstView.backgroundColor = UIColor.blueColor()
    view.addSubview(firstView)

As far as I can see it: firstView is a constant UIView object but even though the object is constant and completly initialised I can change the value of a member of UIView in the next line?

I am confused can anybody explain that to me, because in C++ that would be impossible or do I overlook something?

Regards Ruvi

Ruvi
  • 253
  • 4
  • 15
  • Ok, so with other words let on Objects is like a const Pointer in C++? Not the object itself is const but the pointer holding the object. That is really confusing to me but ok, thanks. Edit: Does a way exist to make also the object itself const? – Ruvi Sep 06 '16 at 14:42
  • Take a look at [This](http://stackoverflow.com/a/24003328/6739471) – Swifty Sep 06 '16 at 14:42

1 Answers1

1

Here is a nice article talking about this: Immutable models in Swift.

In short, classes are reference types and by saying:

let firstView = UIView(frame: firstFrame)

you only make sure the reference firstView is pointing to is not going to change, the internal properties can. This is the difference of classes from structs, structs make sure the value inside isn't ever going to change (unless specified as mutating, but that's off-topic).

S2dent
  • 939
  • 6
  • 9