我正在使用 Xcode 8。我还在使用 Swift 2.3,并将旧版build设置设置为是。我目前没有迁移到 Swift 3。我的应用程序针对 iOS 9.3。我的目标是 watchOS 2.0。
我有两个符合 WCSessionDelegate 的类,它们在 Xcode 7.3.1 中工作得很好。
我看了苹果文档,发现现在这个协议(protocol)有必需的方法,也就是说我需要的是这个:
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState,
error: Error?)
我收到错误:使用未声明的类型“错误”
我认为 Error 是从 Swift 3 开始引入的?不确定,但因为我使用的是 swift 2.3,所以我无法遵守该方法,我对如何解决这个问题感到困惑。让我更加困惑的是,通过将函数放入类中,声称我不符合协议(protocol)的错误消失了......
感谢任何帮助。
最佳答案
在 Xcode 8 中使用 Swift 2.3 会迫使你付出很多努力,Xcode 8 可能会建议使用 Swift 3 版本的方法模板,Apple 不提供 Swift 2 版本的引用...
要在Swift 2.3 中实现delegate 方法,需要查看该方法的Objective-C 版本,并思考Swift 2 是如何自行导入的。
session:activationDidCompleteWithState:error:
Declaration
- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(NSError *)error;
可空性注释在引用中经常被省略,因此您最好检查委托(delegate)的实际 .h header ...
WCSession.h
/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(nullable NSError *)error __IOS_AVAILABLE(9.3) __WATCHOS_AVAILABLE(2.2);
所以,Swift 2 中的方法头应该是这样的:
func session(session: WCSession, activationDidCompleteWithState activationState: WCSessionActivationState, error: NSError?)
如果您不需要在您的应用程序中使用新的 iOS10/watchOS3 功能,我建议您继续使用 Xcode 7 来使用 Swift 2。 (你现在可以提交使用 Xcode 7 构建的应用程序。)否则你最好将你的应用程序迁移到 Swift 3(我知道在很多情况下这可能需要的不仅仅是“一堆努力”......)如果你期待 Xcode 或最新引用的帮助。
关于ios - 尝试符合 WCSessionDelegate 时使用未声明的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39582069/