[swift-evolution] Immutable Structures

Paul Cantrell cantrell at pobox.com
Wed Dec 23 10:51:45 CST 2015


> On Dec 23, 2015, at 10:37 AM, Lino Rosa <lino.aguiar.rosa at gmail.com> wrote:
> 
> Paul Cantrell: Sure, example below. Changing `struct Position` into `class Position` would still compile and print 30 instead. 
> 
> ==============================
> struct Position {
>   var x: Int
>   var y: Int
>   
>   init(x: Int, y: Int) {
>     self.x = x
>     self.y = y
>   }
> }
> 
> func move(var position: Position) {
>   position.x += 20
> }
> 
> var p1 = Position(x: 10, y: 10)
> move(p1)
> 
> print(p1.x) // prints 10
> ==============================

Ah, OK, sure … but why is this a problem? You changed the declaration! Of course it behaves differently. Changing a declaration can transparently change behavior in any number of circumstances. The following code still compiles if you change “Int” to “UInt8,” but it crashes:

    struct Position {
      var x: Int
      var y: Int
      
      init(x: Int, y: Int) {
        self.x = x
        self.y = y
      }
    }

    func move(var position: Position) {
      position.x += 200
    }

    var p1 = Position(x: 100, y: 100)
    move(p1)

    print(p1.x)

I could see this argument having some traction for protocol extensions, which can be attached to structs or classes with wildly different results. Protocols can limit themselves to classes only; can they limit themselves to structs as well? I don’t think so…. That could be a useful language change.

Cheers, P


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151223/b7435dd2/attachment.html>


More information about the swift-evolution mailing list