Chaining optionals produces inexplicable compiler "bug"

I’m at someone’s mercy to explain why the following would not just fail to compile, but put the compiler in a state where it’s incapable of showing a diagnostic message:

import Cocoa

@objc public class Media : NSObject {
    let url = URL(filePath: "/some/path")
}

@objc public class SomeViewController : NSViewController, NSOutlineViewDataSource {
    
    public func outlineView(_ outlineView: NSOutlineView, pasteboardWriterForItem item: Any) -> (any NSPasteboardWriting)? {
        
        // Assume item is an NSTreeNode with instance of Media assigned to its representedObject property
        // Individually, all these work
        
        let treeNode = item as? NSTreeNode
        let media = treeNode?.representedObject as? Media
        let url = media?.url
        
        // Combine them together, and you get "Failed to produce diagnostic for expression; please submit a bug report
        
        return ((item as? NSTreeNode)?.representedObject as? Media)?.url
    }
    
}

I tried a few variants. URL is bridged to NSURL so conformance to NSPasteboardWriting should be included in the box… alas mucking around with ... as (any NSPasteboardWriting) or similar didn’t seem to help.

I refuse to think that I really found a bug in the compiler. I’d rather be schooled/enlightened by a kind soul.

Thanks!

Found how to make it compile, which is to add:

as? (any NSPasteboardWriting)

…but why would the compiler not accept the original form? Is it because the compiler cannot see that Optional<URL> can stand for Optional<any NSPasteboardWriting>?

URL is not any NSPasteboardWriting; NSURL is.

public func outlineView(_: NSOutlineView, pasteboardWriterForItem item: Any) -> (any NSPasteboardWriting)? {
  (((item as? NSTreeNode)?.representedObject as? Media)?.url).map { $0 as NSURL }
}

Thanks @Danny I get that this is one of those cases where the type may be bridged but the compiler expects me to be explicit. (Never loved this btw, I would imagine the intention was to discourage accidental use of NSString methods when working with String). But… any idea why it wouldn’t be able to provide a diagnostic message though? Really worth filing a bug? Seems strange I’d be the first to bump into this.

I don't get that; I get Type of expression is ambiguous without a type annotation.

Running Xcode 26.4 here. Are you on a later version? Pasting that code in a Playground is enough to reproduce the "Failed to produce diagnostic…”

26.3 is good. 26.4 is bad. Real bad. One of the most problematic Xcode releases ever; don't know how it got released, other than the obvious state of the industry and world being what it is. 26.5 is not faring better either.

1 Like

Shucks. Thanks for that insight, I’ll check the betas before filing.