Skip to content

Downcasting to protocol objects #845

Description

@madsmtm

It might be possible to allow converting AnyObject to ProtocolObject<dyn NSObjectProtocol> by checking if the object's class conforms to the protocol, something like:

impl AnyObject {
    pub fn downcast_protocol_ref<P: ProtocolType>(&self) -> Option<&ProtocolObject<P>> {
        let protocol = P::protocol().expect("todo?");
        if msg_send![self, conformsToProtocol: protocol] {
            // SAFETY: Unsure yet if this is all that's required?
            Some(unsafe { transmute(self) })
        } else {
            None
        }
    }
}

// + similar for `Retained::downcast_protocol`

One complication is that ProtocolObject::protocol returns an Option because of #820, unsure how we should handle that? Option<Option<X>> doesn't seem very nice, but neither does panicking!

Might also wanna call it something else? Unsure what this operation is named elsewhere (the standard library doesn't seem to support dyn Any -> dyn MyTrait)?

Related to #843.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-objc2Affects the `objc2`, `objc2-exception-helper` and/or `objc2-encode` cratesenhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions