Optional conforms, but can't cast?

This is confusing me. Am I not saying here that Optional<UUID> conforms to PGArgStringable?

// can't do this:
let optUUID: UUID? = nil
let arg: PGArgStringable = optUUID as! PGArgStringable // error with `as` or `as!`

// even though...

public protocol PGArgStringable {
    func toPGArgString() -> String?
}
extension UUID: PGArgStringable {
    public func toPGArgString() -> String? { self.description }
}
extension Optional where Wrapped : PGArgStringable {
    func toPGArgString() -> String? {
        switch self {
        case .none: return nil
        case .some(let x): return x.toPGArgString()
        }
    }
}

You haven't conformed Optional to PGArgStringable. Here's how to add the conformance:

extension Optional: PGArgStringable where Wrapped : PGArgStringable {
    public func toPGArgString() -> String? {
        switch self {
        case .none: return nil
        case .some(let x): return x.toPGArgString()
        }
    }
}
1 Like

Argh! Thank you. Time for a nap...

A simpler way to write Optional.toPGArgString would be

public func toPGArgString() -> String? {
    self?.toPGArgString()
}
2 Likes