[英]Swift: check return type of generic function
我知道如何檢查命名變量的類型- if var is T
但是找不到如何檢查通用函數的假定返回類型。
現場示例,處理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)")
}
尋找更優雅的方法。
這將工作:
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)")
}
但我不確定它是否比您的優雅。
重載是值得嘗試的事情:
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
}
這樣,您可以在編譯時發現錯誤,而不是在運行時發現致命錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.