The Concept of Up Casting and What’s the Difference Between Using Type Check Operator and Type Cast Operator
I’ve read the “Type Casting” Chapter in “The Swift Programming Language”. It says if the casting succeed, it will “set a new temporary constant”, and “Casting doesn’t actually modify the instance or change its values. The underlying instance remains the same; it’s simply treated and accessed as an instance of the type to which it has been cast.”
So here comes my first question: Is the student
instance actually a copy from marty
, and though student
instance shows as Student
on the outside, it’s still StudentAthlete
inside of it? (And that’s why if I tried to cast student
as SchoolBandMember
I’ll get an error?)
let student = marty as Student
let bandMember = student as SchoolBandMember // error
Another question is, what’s the difference between using type check operator
and type cast operator
? I once assumed that type check operator
is used to check its type on the appearance, and type cast operator
is used to check whether there’s a subclass behind the scene.
So I create an instance from a subclass SchoolBandMember
and upcast it as Student
, then optional click on it, it shows that it’s a Student
. But when I use type check operator
to check if it is
SchoolBandMember
, the program return true
and execute the following program.
let anotherStudent = jessy as Student
func getEveningActivity(student: Student) -> String {
if let bandMember = student as? SchoolBandMember {
return "Practicing for at least \(bandMember.minimumPracticeTime) hours."
} else {
return "Hitting the books."
}
}
getEveningActivity(student: anotherStudent)
// Practicing for at least 2 hours.
func getIdentity(student: Student) -> String {
if student is SchoolBandMember {
return "\(student.firstName) \(student.lastName) is a school band member."
} else {
return "\(student.firstName) \(student.lastName) is not a school band member."
}
}
getIdentity(student: anotherStudent)
// Jessy Catterwaul is a school band member.
So I’m wondering:
- Is the
student
instance actually a copy from marty
, and though student
instance shows as Student
on the outside, it’s still StudentAthlete
inside of it?
- What’s the difference between using
type check operator
and type cast operator
?
Besides, I think I’ve found one of the differences between using type check operator
and type cast operator
. When I use type check operator
on an instance that was up casted from a subclass, I cannot access the property that owns by the subclass. But when I use type cast operator
, the instance becomes a subclass on the outside so I can access the property that belongs to the subclass.
...
func getActiviity(student: Student) -> String {
if student is SchoolBandMember {
return "Practicing for at least \(bandMember.minimumPracticeTime) hours."
// error: value of type 'Student' has no member 'mimimumPracticeTime'
} else {
return "Hitting the books."
}
}