2

(I say "more" in my title because this question is an appendix to my How does Swift ReferenceWritableKeyPath work with an Optional property?.)

In my code, self.iv is an outlet property:

@IBOutlet weak var iv: UIImageView!

Now, will this compile?

    let im = UIImage()
    let kp = \UIImageView.image
    self.iv[keyPath:kp] = im // error

No! We are told that something here must be unwrapped, although it is not entirely obvious what it is:

Value of optional type 'UIImage?' must be unwrapped to a value of type 'UIImage'

But now watch this. Instead of an outlet, I'll just make an image view:

    let im = UIImage()
    let kp = \UIImageView.image
    let iv = UIImageView()
    iv[keyPath:kp] = im

That compiles! Why? What semantic / syntactic difference is there between a UIImageView property and a UIImageView local? Is it that the property is an implicitly unwrapped Optional?

To test that idea, let's "propagate" the unwrapping of self.iv explicitly through a local:

    let im = UIImage()
    let kp = \UIImageView.image
    let iv = self.iv!
    iv[keyPath:kp] = im

That compiles too! But we must use a separate local; merely unwrapping self.iv directly is not sufficient:

    let im = UIImage()
    let kp = \UIImageView.image
    self.iv![keyPath:kp] = im // error

I am not understanding this at all. It goes against my standard beliefs about what an implicitly unwrapped Optional is, and about how a non-Optional may always be assigned to an Optional wrapping the same type. Something about ReferenceWritableKeyPath seems to work oddly with Optional properties but I can't put my finger on it.

So my question is (sorry, maybe a bit vague): can someone justify all these results and make them seem rational and predictable? What are the rules here?

NOTE: Could be the same as https://bugs.swift.org/browse/SR-11184

matt
  • 515,959
  • 87
  • 875
  • 1,141

0 Answers0