Search code examples
iosswiftios7

@objc protocol crashes the swift compiler


I wrote I protocol which was intended to have some @optional methods, but the swift compiler crashes. This works:

protocol SessionDelegate {

    // TODO these should all be optional
    func willOpenSession(session: Session);
    func didOpenSession(session: Session);
    func didFailOpenningSession(session: Session, error: NSError!);

    func willCloseSession(session: Session);
    func didCloseSession(session: Session);
}

This doesn't:

@objc protocol SessionDelegate {

    @optional func willOpenSession(session: Session);
    @optional func didOpenSession(session: Session);
    @optional func didFailOpenningSession(session: Session, error: NSError!);

    @optional func willCloseSession(session: Session);
    @optional func didCloseSession(session: Session);
}

Honestly, having @objc is enough to crash the compiler. Is there any workaround?


Solution

  • Right now your only way around this is to declare the protocol in an Objective-C header file and import the declaration via an Objective-C bridging header.

    Protocol declaration:

    // SessionDelegate.h
    
    @class Session;
    
    @protocol SessionDelegate <NSObject>
    
    @optional
    
    - (void)willOpenSession:(Session *)session;
    - (void)didOpenSession:(Session *)session;
    - (void)didFailOpenningSession:(Session *)session error:(NSError *)error;
    
    - (void)willCloseSession:(Session *)session;
    - (void)didCloseSession:(Session *)session;
    
    @end
    

    Bridging header:

    // MyProject-Bridging-Header.h
    
    #import "SessionDelegate.h"
    

    Conforming class implementation in Swift:

    // Session.swift
    
    class Session {
        // ...
    }
    
    class MySessionDelegate: NSObject, SessionDelegate {
        func willOpenSession(session: Session) {
            // ...
        }
    }