1

Swift has this awesome error that shows up when you try to do something of the form x = x:

class Foo {
    var foo = 1
}

var a = Foo()
a.foo = a.foo // error

This helped me avoid typos where the class had two similarly named properties, and I want to assign one to the other, but mistakenly typed the same one twice.

However, in this particular case:

struct Foo {
    var foo = 1 {
        didSet {
            print("Did set")
        }
    }

    mutating func f() {
        foo = foo
    }
}

var a = Foo()
a.foo = a.foo

It successfully compiles! There isn't even an error on the foo = foo line! If I change Foo to a class, or if I remove the didSet, then the expected error appears. It's just this struct + didSet combination that makes the compiler think "yeah, a.foo = a.foo makes a lot of sense! Let me allow that!"

I found this related post, which is about how to stop getting this error, rather than how to get it.

I also looked on bugs.swift.org, but there were only 3 results, and none of them are related.

I'm using Swift 5.3.2 and Xcode 12.4.

Is there any reason why assigning a struct property to itself is more "OK" than assigning a class property to itself?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I cannot reproduce the error... Simply pasting this into a playground gives the expected error. Is there anything missing? What swift version are you using? – Schottky Jun 22 '21 at 10:03
  • @Schottky I mentioned the Swift version in the question. Time to update Xcode again, huh... – Sweeper Jun 22 '21 at 10:05
  • Oops didn't see, sorry. I was using Xcode 12.5 so that might indeed be the issue – Schottky Jun 22 '21 at 10:06
  • Is the function f() inside foo property observer? Or is it just a typo? – Tushar Sharma Jun 22 '21 at 10:09
  • I tried testing your code in project itself and not in playground, and it’s giving me the same error as with class. I am using Xcode 12.5 though. Verified with playground, still same error. Seems it’s specific to Xcode 12.4. – Tushar Sharma Jun 22 '21 at 10:11
  • Interesting if you add this line ```var a = Foo()``` outside the function and within class level it will not throw an error. – Raja Kishan Jun 22 '21 at 10:18

0 Answers0