简体   繁体   中英

Swift: check return type of generic function

I know how to check type of named variable - if var is T . But can't find how to check supposed return type for generic function.

Live example, dealing with SwiftyJSON, ugly solution:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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