swift - 对象不符合协议(protocol)

标签 swift

struct IsProtocol<Pr> {
    static func implementedInObject<T>(object: T) -> Bool {
        return object is Pr
    }
}


protocol A : class {}
class B : A {}

let b = B()
println(IsProtocol<A>.implementedInObject(b))

返回错误。我应该怎么做才能返回 true?

最佳答案

检查协议(protocol)一致性仅适用于与 Objective-C 兼容的协议(protocol),即用 @objc 指令标记。这是 Swift 语言的局限性,尽管我很希望看到它消失,但我们现在必须使用它。

这里是文档摘录:

You can check for protocol conformance only if your protocol is marked with the @objc attribute, as seen for the HasArea protocol above. This attribute indicates that the protocol should be exposed to Objective-C code and is described in Using Swift with Cocoa and Objective-C. Even if you are not interoperating with Objective-C, you need to mark your protocols with the @objc attribute if you want to be able to check for protocol conformance.

Note also that @objc protocols can be adopted only by classes, and not by structures or enumerations. If you mark your protocol as @objc in order to check for conformance, you will be able to apply that protocol only to class types.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

添加@objc后,它可以正常工作:

struct IsProtocol<Pr> {
    static func implementedInObject<T>(object: T) -> Bool {
        return object is Pr
    }
}

@objc protocol A {}
class B : A {}

let b = B()
println(IsProtocol<A>.implementedInObject(b))

关于swift - 对象不符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618876/

相关文章:

ios - Firebase 使用用户 ID 检索用户图像

ios - 如何在 Swift 中创建一个 List<AnyRealmObject>?

Swift 运行时库与 Swift 标准库

ios - 我的 EXC_BAD_ACCESS (Code = 2) 错误的原因是什么?

ios - UI 测试失败 - 元素和任何后代都没有键盘焦点在 secureTextField 上

ios - 删除图表上线上的折线图值

swift - 进度条触发 100%

json - 使用 Alamofire 和 Codable 进行放置请求

swift - NSMenuItem 设置状态不起作用

ios - 初始化前使用的变量