More about the weird behavior of ReferenceWritableKeyPath with an Optional property

随声附和 提交于 2020-01-23 02:52:27

问题


(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

来源:https://stackoverflow.com/questions/59653363/more-about-the-weird-behavior-of-referencewritablekeypath-with-an-optional-prope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!