With this test harness that mimics `??` and `flatMap`
infix operator ??? : NilCoalescingPrecedence
// Edit: added this overload
@_transparent @_alwaysEmitIntoClient public func ??? <T: ~Copyable>(
optional: consuming T?,
defaultValue: @autoclosure () throws -> T // FIXME: typed throws
) rethrows -> T {
switch consume optional {
case .some(let value): value
case .none: try defaultValue()
}
}
@_transparent @_alwaysEmitIntoClient public func ??? <T: ~Copyable>(
optional: consuming T?,
defaultValue: @autoclosure () throws -> T?
) rethrows -> T? {
switch consume optional {
case .some(let value): value
case .none: try defaultValue()
}
}
extension Optional {
@_alwaysEmitIntoClient public func myFlatMap<E: Error, U: ~Copyable>(
_ transform: (Wrapped) throws(E) -> U?
) throws(E) -> U? {
switch self {
case .some(let y): try transform(y)
case .none: .none
}
}
}
let optional: Int? = 1
let a = (optional ?? 10).flatMap { _ in 0 } // 🔶
let b = (optional ?? 10).myFlatMap { _ in 0 } // 🔶
let c = (optional ??? 10).flatMap { _ in 0 } // ✅
let d = (optional ??? 10).myFlatMap { _ in 0 } // ✅
I am getting the warnings for those:
let optional: Int? = 1
let a = (optional ?? 10).flatMap { _ in 0 } // 🔶
let b = (optional ?? 10).myFlatMap { _ in 0 } // 🔶
but not for these:
let c = (optional ??? 10).flatMap { _ in 0 } // ✅
let d = (optional ??? 10).myFlatMap { _ in 0 } // ✅
Which suggests there's some difference between my custom ??? operator and real ?? operator.. but what exactly is that difference and could ?? be modified to not have such behaviour?