下面的代码片段展示了我试图解决的问题。
import Foundation
protocol Printable {
func className() -> String
}
class SomeType: Printable {
func className() -> String {
return "SomeType"
}
}
class List<T> {
}
extension List where T: SomeType {
func className() -> String {
return "List<SomeType>"
}
}
func test(type: Any, message: String) {
guard type is Printable else {
print("\(message): ERROR")
return
}
print("\(message): SUCCESS")
}
let s: Any = SomeType()
test(type: s, message: "#1")
let slist1: Any = List<Any>()
test(type: slist1, message: "#2")
let slist2: Any = List<SomeType>()
test(type: slist2, message: "#3")
我怎样才能得到这个:
> #1: SUCCESS <--- as expected
> #2: ERROR <--- it's okay
> #3: SUCCESS <--- I am getting ERROR instead
似乎向这一行添加一个协议(protocol)就可以解决问题:
extension List: Printable where T: SomeType { // COMPILE ERROR
但不幸的是,这是不允许的。
另一种方法是使用:
extension List where T: Printable { // COMPILES OK in Swift 2.3 but doesn't work. COMPILE ERROR in Swift 3.0
但还是没能通过考试。
我还能做什么来向受约束的泛型类型添加协议(protocol)?
最佳答案
现在我们有了 Swift 4.2,这是一个更新的答案,现在添加了条件一致性作为一项功能。
来自他们的 spec on Github , 这种代码现在有效
extension List : Printable where T: SomeType {
func className() -> String {
return "List<SomeType>"
}
}
关于swift - Swift 中条件一致性的解决方法(原为 : Adding protocol to a constrained generic types),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671878/