2016-09-14 23 views
1

我知道如何檢查指定變量的類型 - if var is T。但無法找到如何檢查通用函數的假定返回類型。Swift:檢查返回類型的通用函數

活生生的例子,處理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)") 
} 

尋找更好的方法。

回答

2

這會工作:

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 
} 

有了這個,你可以找到的錯誤在編譯的時候,而不是在運行時獲得的致命錯誤。

+0

感謝'T.self'!至於專業化,我不想複製函數,因爲代碼中有共同的邏輯。我用協議擴展來解決它:'' – brigadir