Chapter 15: Casting

I’m having trouble replicating the the results that are supposed to happen on page 216 of the pdf:

oboePlayer as Student
(oboePlayer as Student).minimumPracticeTime
// ERROR: No longer a band member!
hallMonitor as? BandMember
(hallMonitor as? BandMember)?.minimumPracticeTime // 4 (optional)
hallMonitor as! BandMember
// Careful! Failure would lead to a runtime crash.
(hallMonitor as! BandMember).minimumPracticeTime // 4 (force unwrapped)

I see how to use “as” to cast to a superclass. But when I try to use “as?” or “as!”, to downcast, I’m unable to get the property “minimumPracticeTime” to show. In fact, I think whenever I run either downcast, I’m getting nil as the value. Any help?

Hi! Have the same problem.
Did you find a solution to the problem?

Nope. I’ve tried it at least one other time since this first posting. I think it’s a bug in the writing, but I still struggle to specify why this doesn’t work as is written.

I’m currently updating this chapter for Swift 4 at the moment and the code works as expected for me in the first place and to begin with:

  • It actually crashes in the first case when you use as in order to upcas.t
  • It returns an optional wrapped value (not nil) in the second case when you use as? in order to optional downcast.
  • It finally returns the optional’s unwrapped value in the third case when you use as! in order to force downcast the whole thing after all.

Please let me know if you are still having the issue at this point after all and if you are still getting nil when running the above code in a playground. Thank you - much appreciated! :]