【问题标题】:Swift class does not conform to Objective-C protocol with error handlingSwift 类不符合带有错误处理的 Objective-C 协议
【发布时间】:2015-10-28 04:59:18
【问题描述】:

我有Objective-C协议

@protocol SomeObjCProtocol
- (BOOL) doSomethingWithError: (NSError **)error;
@end

还有Swift

class SwiftClass : SomeObjCProtocol
{
    func doSomething() throws {    
    }
}

编译器给了我一个error

类型 'SwiftClass' 不符合协议 'SomeObjCProtocol'"

有什么办法可以解决这个错误吗? 我正在使用XCode 7 Beta 4

【问题讨论】:

  • 不应该返回一个布尔值吗?
  • 没有。 Swift 类中的函数由 xcode 自动完成。另见documentation
  • 所以你使用的是 Swift 2.0?
  • func buyFavoriteSnack(exception: bool) throws 在实现类中 func buyFavoriteSnack(exception: bool) throws { let snapName = favoriteSnacks[person] ?? "Candy Bar" 试试 vend(itemNamed:snackName) } 或者直接参考developer.apple.com/library/prerelease/ios/documentation/Swift/…

标签: objective-c swift error-handling protocols swift2


【解决方案1】:

遇到该错误消息时,问题的根源之一可能是符合 Objetive C 协议的 Swift 类不是从 NSObject 继承的。

【讨论】:

    【解决方案2】:

    有两个问题:

    • Swift 2 将 func doSomething() throws 映射到 Objective-C 方法 - (BOOL) doSomethingAndReturnError: (NSError **)error;,即 与您的协议方法不同。
    • 必须使用@objc 属性将协议方法标记为“Objective-C compatible”。

    有两种可能的解决方案:

    解决方案一:将Objective-C协议方法重命名为

    @protocol SomeObjCProtocol
    - (BOOL) doSomethingAndReturnError: (NSError **)error;
    @end
    

    解决方案 2: 保持 Objective-C 协议方法不变,并为 Swift 方法指定 Objective-C 映射 明确:

    @objc(doSomethingWithError:) func doSomething() throws {
        // Do stuff
    }
    

    【讨论】:

    • 两种解决方案都有效。谢谢你。虽然解决方案 1 有点奇怪,因为根据 documentation 后缀 WithError 应该也可以工作。
    • @Joey:我假设 protocol 方法的规则略有不同。在这里,Swift 方法被映射到 Objective-C(以检查一致性),而不是相反。
    • 对我来说,问题是我拼错了小写和大写的方法名称。类似:- (void) thisClass:(Class *)class DidSendStuff:(Stuff *)stuff,我正在尝试使用 - (void) thisClass:(Class *)class didSendStuff:(Stuff *)stuff注意 DID SEND STUFF 的小写和大写
    猜你喜欢
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多