Problem with generics

  1. 5 years ago

    I think I discovered a problem with generics.

    Assume I want to pull a value from a dictionary, and return the value as a String, if possible. I can this:

    func stringValueFromDictionary(dictionary:[String: AnyObject], key: String, defaultValue: String) -> String {
            var result:String = defaultValue;
            
            if let neobj: AnyObject = dictionary[key] {
                if let neval = neobj as? String {
                    result = neval as String;
                }
            }
            
            return result;
        }

    I can do the same for Int or any other type. However, now if I try to make that generic as follows, it'll fail:

    func valueFromDictionary<T>(dictionary:[String: AnyObject], key: String, defaultValue: T) -> T {
            var result:T = defaultValue;
            
            if let neobj: AnyObject = dictionary[key] {
                if let neval = neobj as? T {
                    result = neval as T;
                }
            }
            
            return result;
        }

    In particular, it fails on the "if let neval = neobj as? T" line, which will never result in true.

    Intentional behavior? Seems like a bug, but I'm not certain.

  2. 4 years ago
    Edited 4 years ago by tomkowz
    func valueFromDictionary<T>(dictionary:[String: T], key: String, defaultValue: T) -> T {
        return dictionary[key] ?? defaultValue
    }
    
    var dict: Dictionary<String, String> = ["A": "B", "C": "D"]
    
    valueFromDictionary(dict, "A", "Z") // B
    valueFromDictionary(dict, "Z", "Y") // Y

or Sign Up to reply!