Proposal for generic protocols

Joe, I had an idea to replace _ObjectiveCBridgeable with two protocols in order to pave the way for bridging using as or as? operators from other language types like C++'s map or Python's dict. But I see there is no support for generic protocols. The current design which uses associated types does not fit for this application. We can also use this design to replace protocols like CustomStringConvertible.

See this:

protocol LoselessConvertible<T> {
    func cast() -> T
}

protocol Convertible<T> {
    func cast() -> T?
}

We can use these protocols to replace _ObjectiveCBridgeable internal protocol. For example, the bridiging mechanism for NSData and Data will be:

extension Data: LoselessConvertible<NSData> {
    func cast() -> NSData {
        return NSData(data: self)
        // or 
        // return _backing.bridgedReference(_sliceRange)
    }
}

extension Data: LoselessConvertible<[UInt8]> {
    func cast() -> [UInt8] {
        return [UInt8](self)
    }
}

extension NSData: LoselessConvertible<Data> {
    func cast() -> Data {
        return Data(referencing: src)
    }
}

extension Array: LoselessConvertible<Data> where Element == UInt8 {
    func cast() -> Data {
        return Data(bytes: self)
    }
}

Another use can be casting from C types:

extension UnsafeMutablePointer<UInt8>: LoselessConvertible<String> {
    func cast() -> String {
        return String(cString: self)
    }
}
1 Like