Programming in Swift: Functions & Types

Jan 4 2022 Swift 5.5, iOS 15, Xcode 13

Part 3: Enumerations

24. More Switch Statements

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 23. Switch Statements Next episode: 25. Challenge: Switch Statements

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

You’ve seen how easy it is to use a switch statement with enumerations. But what about other types of values? If you find yourself creating long if statements with lots of else clauses, a switch statement might be a better choice. Let’s see what else you can do with switch statements, to help you decide.

func getDescription(for number: Int) -> String {

}
switch number {
  
}
break
return "No Description"
getDescription(for: 15)
case 0:
  return "Zero"
getDescription(for: 0)
case 1...9:
  return "Between 1 and 9"
getDescription(for: 4)
case let negativeNumber 
case let negativeNumber😺 where negativeNumber < 0:
  return "Negative"
getDescription(for: -52)
42 case _ where number > .max / 2:
  numberDescription = "Very large!"
getDescription(for: Int.max)
let number = Int.max
let numberIsEven: Bool
switch number % 2 {

}
case 0:
  numberIsEven = true
default:
  numberIsEven = false
func pointCategory(for coordinates: (Double, Double))
func pointCategory(for coordinates: (Double, Double))😺 -> String {

}
switch coordinates {
default:
  return "No Category"
}
71 case (0, 0):
  return "Origin"
case (let x, 0):
  return "On the x-axis at \(x)"
case (0, let y):
  reutrn "On the y-axis at \(y)"
pointCategory(for: (0, 0))
pointCategory(for: (50, 0))
pointCategory(for: (0, 3))
case let (x, y):
  return "No zero coordinates. x = \(x), y = \(y)"
pointCategory(for: (-4, 17))
case let (x, y) where y == x * x:
  pointCategory = "Along y = x ^ 2"
pointCategory(for: (2, 4))
😺case (_, let y) where coordinates.0 == y:
  pointCategory = "Along y = x"🛑
case let (x, y) where y == x * x
77 case _ where coordinates.0 == coordinates.1:
  pointCategory = "Along y = x"
pointCategory(for: (6, 6))