The ability of if statements to conditionally unwrap optionals can be chained together to produce some useful and concise code. The following example is a bit contrived, but it illustrates how we can use a single if statement to unwrap a chain of optional values.
When you play a game of pool, called a frame, the type of the first ball you pot becomes the type you need to pot for the rest of the frame, and your opponent has to pot the opposite type.
Let's define a frame of pool and say that we want to track what type of ball each player will be potting:
class PoolFrame {
var player1BallType: PoolBallType?
var player2BallType: PoolBallType?
}
We will also create a PoolTable object that has an optional currentFrame property, which will contain information about the current frame if one is in progress:
class PoolTable {
var currentFrame: PoolFrame?
}
We now have a pool table that has an optional frame and a frame that has an optional...