Multiline Nested Comments in Swift

Asif Noor
2 min readJul 31, 2021

I was reading Swift documentation and found out that it supports nested multiline comments which only few other programming languages like Kotlin support. Multiline nested comments example at Swift official docs website

/* This is the start of the first multiline comment.  /* This is the second, nested multiline comment. */This is the end of the first multiline comment. */

By looking at this example, I was puzzled that why would someone add a multiline comment inside already block of commented code. But since Apple has introduced this support, there must be some strong reason and scenarios where it is very helpful. I thought may be I am reading it the wrong way. How about if I have few lines of code already commented as shown in following example

Code Example 1:

func printWelcomeInfo() {let welcomeMessage = "Hello World", age = 10, email = "a@gmx.com"print(welcomeMessage, age, email)/*print(welcomeMessage, email, terminator: " ")print(age)print(isWorking)*/let x = 10, y = 2, z = 5print(x, y, z)}

Now, I want to comment whole body of func. Since, Swift supports nested multiline comments, we can add multiline comments to already commented code and it would look like following

Code Example 2:

func printWelcomeInfo() {/*let welcomeMessage = "Hello World", age = 10, email = "a@gmx.com"print(welcomeMessage, age, email)/*print(welcomeMessage, email, terminator: " ")print(age)print(isWorking)*/let x = 10, y = 2, z = 5print(x, y, z)
*/
}

We are able to add multiline comment to already commented code easily. From Swift official documentation,

Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.

There is another benefit of nested multiline comments, for example after couple of days, you decided to restore the code to original state (Code Example 1), you can easily remove external comment while leaving the internal commented code as it is.

I hope it helps. Thanks for reading !

--

--

Asif Noor

I am working as an iOS engineer and love to write about iOS and life.