You cannot not inherit description
, but you can assign a value nil
to it, and simply ignore it.
If you can modify Model
, you can change its init
to
class Model {
// ...
init(userId: Int, username: String, description: String? = nil)
// ...
}
Since description is optional, we set it to nil
by default, so ModelDetail
doesn't need to set it at all:
class ModelDetail: Model {
let url: String
let detail: String
init(url: String, detail: String, userId: Int, username: String) {
self.url = url
self.detail = detail
super.init(userId: userId, username: username)
}
}
If you cannot change Model
, then ModelDetail
can invoke Model
's init with nil
for description:
class ModelDetail: Model {
// ...
init(url: String, detail: String, userId: Int, username: String) {
// ...
super.init(userId: userId, username: username, description: nil)
}
}
If you want to strictly adhere to the inheritance rules (which do not allow for "unused" fields), then you need to separate description
from the model ModelDetail
will be inheriting from. I.e.:
- Have a base model, which only has
userId
and username
- Both
Model
and ModelDetail
will inherit from that base model, rather than each other:
class BasicModel {
let userId: Int
let username: String
init(userId: Int, username: String) {
self.userId = userId
self.username = username
}
}
class Model: BasicModel {
private let description: String?
init(userId: Int, username: String, description: String?) {
self.description = description
super.init(userId: userId, username: username)
}
}
class ModelDetail: BasicModel {
let url: String
let detail: String
init(url: String, detail: String, userId: Int, username: String) {
self.url = url
self.detail = detail
super.init(userId: userId, username: username)
}
}