Discover the versatility of the switch statement in Swift. Switch over individual values, ranges, and tuples, and use basic to advanced pattern matching in case clauses.
- [Narrator] The switch statement provides…a more concise syntax for handling multiple possible states…than chained if, else if statements.…Remember that test score example I showed you…in the if conditionals video?…I'm going to re-implement it using a switch statement.…To define a switch statement, write the switch keyword,…followed by the value you want to switch on,…and curly braces to enclose the switch's body.…Then define one or more case clauses in the body…to match each possible value, or range of values.…Each case clause is defined by writing the case keyword,…followed by a value, or pattern-matching expression,…a colon, and then an executable expression,…typically written on the next line.…
I'll print the 100 emoji if the test score is 100.…Now we'll finish up the implementation…by using ranges to define each range of test scores…for each letter grade.…If testScore falls within a range that case will match…and it's code will be executed.…Notice that I'm not writing a break control transfer…statement in each case, as is typically required…
Learn how to write code, understand Swift's key concepts and best practices, and strengthen your programming problem-solving skills. Instructor Scott Gardner teaches the fundamentals, so you'll be prepared to develop applications for iOS, macOS, and other platforms. Completing this course will enable you to not only write first-class code, but to think like a Swift developer.
- Creating playgrounds
- Defining variables and constants
- Working with characters and strings
- Working with collections and groups
- Using operators and defining custom operators
- Controlling program flow
- Defining functions and closures
- Working with classes, structures, and enumerations
- Adopting protocols
Skill Level Beginner
1. Get Started
2. Variables and Constants
3. Characters and Strings
4. Collections and Tuples
6. Control Flow
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.