我想要一个定义一些方法和属性的协议。但是,属性类型和方法返回类型可能在符合所述协议的不同类之间有所不同。例如:A.getContent()
可能会返回String
类型的值,但B.getContent()
可能会返回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
}
}
答案 0 :(得分:7)
我认为你正在寻找协议中的泛型。
您可以动态地将类型与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
如果你看一下这个例子,当你将函数后面的Type放在Content的类sun中时,协议Content将是这一种类型
<强>更新强>
我正在使用&#34; swiftly&#34;语法而不是传统的getContent
。
protocol Content{
associatedtype T
var content:T { get }
}
class A: Content {
var content:String{
return "Hello World"
}
}
class B: Content {
var content:Int{
return 42
}
}
A().content //"Hello World"
B().content //42
答案 1 :(得分:1)
您可以使用泛型和元类型:
protocol Content {
func getContent<T>(ofType: T.Type) -> T?
}
class A: Content {
func getContent<T>(ofType: T.Type) -> T? {
return "Im a String" as? T ?? nil
}
}
class B: Content {
func getContent<T>(ofType: T.Type) -> T? {
return 1234 as? T ?? nil
}
}
let aClass = A()
let aValue = aClass.getContent(ofType: String.self) // "Im a String"
let bClass = B()
let bValue = bClass.getContent(ofType: Int.self) // 1234