Note about `unowned` could provide safety warning

Hello! (just quickly want to mention that I enjoy the swift.org website a loot, it helped me started iOS career)

Today I was reading " Weak and Unowned References" section of this page and noticed this note

NOTE

If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference.

In the presented example however that might result in and unexpected issue while assigning HTMLElement asHTML closure to some variable that will outlive the origin closure holder example:

var heading: HTMLElement? = HTMLElement(name: "heading")
var htmlHeadingRenderer = heading?.asHTML

print(htmlHeadingRenderer?())
heading = nil

print(htmlHeadingRenderer?()) // crash

I think it might be worth giving a hint about such case scenario, wdyt?

Not the best unowned usage indeed. I'd change that example to something else if it wants to showcase the unowned usage. As for that example, to avoid the crash either change to weak or just expose a direct var html: String { .. } property.

1 Like

Yup exactly! I just wanted to highlight, that the note might be misleading as it says "If the captured reference will never become nil" and example below uses unowned but as showed above can cause unexpected issues