[英]Swift generics. How to Specify output type?
I have, for example, enum
and what I want to archive is that each enum case
can give me some different output type for, let's say a function.例如,我有
enum
,我想要存档的是每个enum case
可以给我一些不同的输出类型,让我们说一个函数。 Code example:代码示例:
protocol MyType: Codable {
var id: String {get set}
}
struct Type1: MyType {
var id: String
var name:String
}
struct Type2: MyType {
var id: String
var amount: Int
}
enum ReturnType {
case first, second
//Option 1
func getElement() -> MyType {
switch self {
case .first:
return Type1(id: "1", name: "Name")
case .second:
return Type2(id: "2", amount: 10)
}
}
//Some crap is here - don't pay attention
func test<T:MyType>(data: T) -> T {
return data
}
}
//Option 2
func getElement(ofType type: ReturnType) -> MyType {
switch type {
case .first:
return Type1(id: "1", name: "Name")
case .second:
return Type2(id: "2", amount: 10)
}
}
let test1 = ReturnType.first.getElement() as! Type1
let test2 = ReturnType.second.getElement()
let test3 = getElement(ofType: .first)
So currently only test1
is Type1
but test2
and test3
is MyType
I want to archive strong typing without forcing that with as!
所以目前只有
test1
是Type1
但test2
和test3
是MyType
我想存档强类型而不用as!
强制它as!
I was trying to do it with generics but didn't get any success.. Any thoughts?我试图用泛型来做,但没有取得任何成功..有什么想法吗? Much appreciated!
非常感激! Thanks!
谢谢!
you can do the following:您可以执行以下操作:
enum ReturnType {
case first, second
//Option 1
func getElement<T: MyType>() -> T {
switch self {
case .first:
return Type1(id: "1", name: "Name") as! T
case .second:
return Type2(id: "2", amount: 10) as! T
}
}
}
//Option 2
func getElement<T: MyType>(ofType type: ReturnType) -> T {
switch type {
case .first:
return Type1(id: "1", name: "Name") as! T
case .second:
return Type2(id: "2", amount: 10) as! T
}
}
after that when you call the func you just need to declare what type you want the variable as:之后,当您调用 func 时,您只需要声明您想要变量的类型:
let test1: Type1 = ReturnType.first.getElement()
let test2: Type2 = ReturnType.second.getElement()
let test3: Type1 = getElement(ofType: .first)
hope it helped希望它有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.