First of all let's clean up your code
class Parent {
var a:String?
var b:String?
init(a:String?, b:String?) {
self.a = a
self.b = b
}
}
class Child: Parent{
var c: String?
}
Answer
With this code you create a Parent object and you put it into the parent
constant.
let parent = Parent(a:"1111",b:"22222")
Then you try to cast parent as Child. But Parent
is NOT a Child
. So the cast will fail.
if let child = parent as? Child {
print(child)
}
Conclusion
class Child: Parent { ...}
you are saying that a Child
is also a Parent
.
NOT that a Parent
is a Child
.
Update
If you want to create a Child
object using a Parent
object (if this makes sense for your business logic) here's the code
class Child: Parent{
var c: String?
init(parent:Parent, c:String) {
super.init(a: parent.a, b: parent.b)
self.c = c
}
}
let parent = Parent(a: "a", b: "b")
let child = Child(parent: parent, c: "c")
child.a // "a"
child.b // "b"
child.c // "c"
has-a
instead of is-a
Another possible solution is avoiding subclassing, here's the code
struct Parent {
var a:String?
var b:String?
}
struct Child {
var c: String?
var parent: Parent
}
Now Child
is not a Parent
but contains a Parent
You probably should rename them
Now given a parent
let parent = Parent(a: "a", b: "b")
you can easily create a Child
let child = Child(c: "c", parent: parent)
And this is how you use the child
child.parent.a // "a"
child.parent.b // "b"
child.c // "c"