In the following example, I have a class Parent and a subclass Child. Next, I create an array of type [Parent] and fill it with a Child,
When I print the type of the element in the array, it prints Child. However, when I try to access the name property of that element, I can't do so because the compiler says that element is of type Parent.
I understand that a Child is of type Parent, but why is the compiler presenting it differently in the different print statements? How would I be able to access the .name property of Child in the array?
class Parent { }
class Child: Parent {
let name = "bob"
}
var arr: [Parent] = [ Child() ]
print(type(of: arr[0])) // Prints: "Child()"
print(arr[0].name) // error: value of type 'Parent' has no member 'name'
CodePudding user response:
type(of: arr[0]) is executed at the runtime, that's why it prints the type description as "Child". arr[0].name is executed at the compile time. Compiler only knows that arr is an array of Parent so only Parent properties are available.
CodePudding user response:
In the statement print(arr[0].name), the only type known for arr[0] is Parent, and Parent has no name property. You have to tell Swift to treat arr[0] as a Child if possible, using an as? cast:
print((arr[0] as? Child)?.name)
UPDATE
type(of: arr[0]) returns the dynamic (runtime) type of arr[0], by inspecting the reference object header of arr[0].
