0

Why cannot we change the instance properties from within the instance methods in Swift for the Value Types like struct, enums? Why does the same thing works for reference types like Classes?

enter image description here

Doing mutating func in struct makes it act like a class instance method?

Anuj
  • 6,987
  • 3
  • 22
  • 25
  • 3
    You have to mark the method as "mutating". – This *must* have been asked and answered before ... – Martin R Feb 06 '15 at 13:41
  • I am asking the reason to why does this differ, I know doing mutating does make it work and thats what the second part of my question does say? Is it an OOPs concept or just pertain to Swift? – Anuj Feb 06 '15 at 13:44
  • Then I misunderstood your question, sorry. – Classes are *reference types*, and their methods can always modify the state, in contrast to structs which are *value types* where the method must be marked as mutable. – Martin R Feb 06 '15 at 13:49
  • So it pertains specifically to Swift value types, because I think values types like structs and enums are this powerful in Swift only – Anuj Feb 06 '15 at 13:53
  • Does this answer your question: http://stackoverflow.com/questions/24035648/swift-and-mutating-struct ? – Martin R Feb 06 '15 at 13:56
  • Yup, pretty much. Thanks – Anuj Feb 06 '15 at 17:41

1 Answers1

1

The design of Swift was heavily influenced by functional programming languages such as Haskell, F#, Scala, Erlang, etc. One of the core principles of functional programming is that data is immutable. Functions operate on the data and produce new values as a result rather than modifying the data in place which eliminates side effects. These influences are seen in many places in Swift such as immutable value types, the map function, lambda functions, optional values, and pattern matching (switch in Swift).

Wayne Tanner
  • 1,346
  • 11
  • 18