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.
添加@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/