-1

I am trying to create a Response Base to contain API request but I get error Non-nominal type 'T' does not support explicit initialization when using codable. This used to work with a third party library but I am swapping out old data for new one.

class ResponseBase: Codable {
    var status: String?
    var message: String?
    var pagination: Pagination?

    var isSucessful: Bool {
        return status == "success"
    }

    struct ErrorMessage {
        static let passwordInvalid = " Current password is invalid."
        static let loginErrorIncorrectInfo = " Incorrect username/password."
        static let loginErrorAccountNotExist = " Invalid request"
    }
}

class Response<T: Codable>: ResponseBase {
    var data: T?

    public func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) {
        switch key {
        case "data":
            data = value as? T
        default:
            print("---> setGenericValue '\(value)' forUndefinedKey '\(key)' should be handled.")
        }
    }

    public func getGenericType() -> Codable {
        return T()
    }
}
King
  • 1,885
  • 3
  • 27
  • 84

2 Answers2

0
public func getGenericType() -> T.Type {
    return T.self
}
mmr118
  • 496
  • 4
  • 14
0

The error message means just what it says. Merely conforming to Codable does not guarantee that init exists, so saying T() is illegal. You must make that guarantee yourself. For example:

protocol CodableAndInitializable : Codable {
    init()
}
class ResponseBase: Codable {
    // ....
}
class Response<T: CodableAndInitializable>: ResponseBase {
    var data: T?
    // ....
    public func getGenericType() -> Codable {
        return T()
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Maybe this is the answer you're looking for but here you are returning a new object of type `T`. To get the *type* you should return the *type*? – mmr118 Sep 18 '19 at 16:42
  • @mmr118 I agree, but my goal was merely to get rid of the error given the OP's original code. – matt Sep 18 '19 at 16:50