Search code examples
swiftgenericsreturn-typetypechecking

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.


Solution

  • 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.