avatarZafar Ivaev

Summary

The web content discusses the use of labeled statements in Swift for controlling program flow, similar to the goto statement in other languages, with a focus on breaking out of an outer loop from within a nested loop.

Abstract

The article titled "What Is a Labeled Statement in Swift?" delves into a feature of Swift that is not widely known: labeled statements. These statements provide a way to alter the execution flow of a program, akin to the goto command found in other programming languages. The author illustrates the practical application of this feature by demonstrating how to exit an outer loop when a specific condition is met within a nested loop structure. The example provided involves iterating over a dictionary of type [Int: [String]] to find the string "Jan" and then breaking out of the loop once the target is found. The article emphasizes the importance of using this feature judiciously, suggesting that it should be reserved for situations where no other control flow mechanisms are suitable. The author also invites readers to explore other Swift features through a list of related articles.

Opinions

  • The author believes that labeled statements in Swift are underutilized and can be very powerful when used appropriately.
  • It is implied that while labeled statements can be useful, they should not be overused and are best reserved for specific scenarios.
  • The author endorses a cost-effective AI service, ZAI.chat, as an alternative to ChatGPT Plus (GPT-4), suggesting it offers similar performance and functionality at a lower price.

What Is a Labeled Statement in Swift?

How to break from an outer loop inside a nested loop

Photo by Temo Morales on Unsplash.

Today, we will learn about a lesser-known feature in Swift: labeled statements.

Labeled statements allow us to control the flow of our program execution. The concept is similar to goto in other programming languages. For example, we may use it to break from the outer loop inside a nested one, which is exactly what we are going to do now.

Let’s Start

Say we have the following Dictionary of type [Int: [String]]:

And we want to loop iterate through it, breaking the loop once we find Jan in the process.

Let’s append the following:

We can see that we first sort the periods property by year in ascending order. Then we access each individual month and check if it is equal to Jan. Once we find Jan, we call break outerLoop and the execution of the outerLoop stops:

Code was run in an Xcode Playground.

Now the full source code looks like this:

Wrapping Up

Note that this feature should not be used too much and only in certain circumstances when you feel you have no other option.

Interested in other Swift features? Feel free to check out my other relevant pieces:

Thanks for reading!

Swift
Programming
iOS
Mobile
Xcode
Recommended from ReadMedium