Error when nil coalessing multiple types with common protocol

I've got multiple types that conform to the same protocol and I'm trying to use the nil coalescing operator to get the first one where the failable initializer succeeds. Heres and example that shows it off in a playground.

protocol P {}
struct A: P { init?() { return nil } }
struct B: P { init?() { return nil } }
struct C: P {}

let value: P = A() ?? B() ?? C() // error

The full console output I get is

error: macOS.playground:247:20: error: value of optional type 'P?' must be unwrapped to a value of type 'P'
let value: P = A() ?? B() ?? C()
                   ^

macOS.playground:247:20: note: coalesce using '??' to provide a default when the optional value contains 'nil'
let value: P = A() ?? B() ?? C()
                   ^
               (                ) ?? <#default value#>

macOS.playground:247:20: note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
let value: P = A() ?? B() ?? C()
                   ^
               (                )!

It feels like it should work but the compiler is complaining about it. The weird thing is there's a couple simple workarounds

let value: P = (A() ?? B()) ?? C() // works
let value: P = A() as P? ?? B() ?? C() // works

Is there a way to do this without the extra parentheses or using as?

Sounds like a bug to me. Mind filing at https://bugs.swift.org?

Terms of Service

Privacy Policy

Cookie Policy