我想有一个定义一些方法和属性的协议.但是,属性类型和方法返回类型可能在符合所述协议的不同类之间有所不同.例如:A.getContent()可能返回type的值String,但B.getContent()可能返回type的值Int.在下面的示例中,我使用了该类型Any.这在Swift中是可能的还是这是一种完全错误的方法?也许用泛型?
protocol Content {
func getContent() -> any
}
class A: Content {
func getContent() -> String {
return "Im a String"
}
}
class B: Content {
func getContent() -> Int {
return 1234
}
}
Run Code Online (Sandbox Code Playgroud)
我想你正在寻找协议中的泛型.您可以将动态类型与之关联associatedtype,例如
protocol Content{
associatedtype T
func getContent()-> T
}
class A: Content {
func getContent() -> String {
return "Hello World"
}
}
class B: Content {
func getContent() -> Int {
return 42
}
}
A().getContent() //"Hello World"
B().getContent() //42
Run Code Online (Sandbox Code Playgroud)
如果你看一下这个例子,当你在内容的类sun中放入Type after函数时,协议Content将是这一种类型
| 归档时间: |
|
| 查看次数: |
1014 次 |
| 最近记录: |