繁体   English   中英

Swift:检查泛型函数的返回类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM