问题
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?
回答1:
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) {
// ...
}
}
回答2:
Apology, scratch my previous edit, try following instead:
@objc(PSessionDelegate)
protocol PSessionDelegate {
@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);
}
class ViewController: UIViewController, PSessionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
来源:https://stackoverflow.com/questions/24564830/objc-protocol-crashes-the-swift-compiler