[英]Swift: check return type of generic function
I know how to check type of named variable - if var is T
. 我知道如何检查命名变量的类型-
if var is T
But can't find how to check supposed return type for generic function. 但是找不到如何检查通用函数的假定返回类型。
Live example, dealing with SwiftyJSON, ugly solution: 现场示例,处理SwiftyJSON,丑陋的解决方案:
func getValue<T>(key: String) -> T? {
let result: T // so ugly approach...
if result is Bool {
return json[key].bool as? T
}
if result is Int {
return json[key].int as? T
}
if result is String {
return json[key].string as? T
}
fatalError("unsupported type \(result.dynamicType)")
}
Looking for more elegant approach. 寻找更优雅的方法。
This would work: 这将工作:
func getValue<T>(key: String) -> T? {
if T.self is Bool.Type {
return json[key].bool as? T
}
if T.self is Int.Type {
return json[key].int as? T
}
if T.self is String.Type {
return json[key].string as? T
}
fatalError("unsupported type \(T.self)")
}
But I'm not sure it's any more elegant than yours. 但我不确定它是否比您的优雅。
Overloading is something worth trying: 重载是值得尝试的事情:
func getValue(key: String) -> Bool? {
return json[key].bool
}
func getValue(key: String) -> Int? {
return json[key].int
}
func getValue(key: String) -> String? {
return json[key].string
}
With this, you can find errors in compile time, rather than getting fatal errors in runtime. 这样,您可以在编译时发现错误,而不是在运行时发现致命错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.