Search code examples
swiftnsuserdefaultsswift4.2

Cannot convert return expression of type '[Favorite.Type]' to return type '[Favorite]'


I want to make a general function for getting Elements from UserDefaults that are conforming to the NSObject and NSCoding Protocol. But when I want to use that function I get this error

    func getFavorites() -> [Favorite] {
        return get(type: Favorite, forKey: UD_FAVORITES)
    }

Cannot convert return expression of type '[Favorite.Type]' to return type '[Favorite]'

That's my UserDefaults Extension:

    func get<T>(type: T, forKey key: String) -> [T] {
        if let data = self.object(forKey: key) as? Data {
            do {
                let tData = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! [T]
                return tData
            } catch {
                debugPrint(error)
                return [T]()
            }
        } else {
            print("EMPTY \(key)")
            return [T]()
        }
    }

Solution

  • The type of type must be T.Type

    func get<T>(type: T.Type, forKey key: String) -> [T] { ...
    

    and you have to call it

    return get(type: Favorite.self, forKey: UD_FAVORITES)
    

    Actually you don't need the parameter, this is Swift, the compiler can infer the type (specified by the return type [Favorite])

    func get<T>(valueForKey key: String) -> [T] {
    

    and

    return get(valueForKey: UD_FAVORITES)
    

    And there is

    if let data = self.data(forKey: key) {