1022

In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, or do I have to use ugly comments?

7
  • 25
    It's really important for organize our long code. Commented Jun 3, 2014 at 14:21
  • 2
    For other Swift and Xcode newbies I'll just mention that the "symbol navigator" that everyone is talking about is one you get when you click on the rightmost thing in the "jump bar" at the top of the editing window. It is not the symbol navigator in the left panel. Commented Jan 21, 2017 at 1:00
  • 1
    @Moritz iOS is most google search keyword even tvOS developer also search like what is "param mark" in ioS ? this question ask most of new developer for learn swift . so i think iOS and Swift both are good keyword for this question . Commented Jan 12, 2018 at 5:03
  • 3
    @HarshilKotecha Swift is a programming language independent of the platform it runs on. Pragma mark is part of Swift and can be used on Linux, macOS and other Apple platforms including iOS. It would be ridiculous to tag this question with any of these platforms because pragma mark is a feature of Swift itself, not of the platform. iOS is only one of the many platforms where Swift runs. This is important to understand. This question is not about iOS, and is not about Linux or macOS either. It's about Swift. Commented Jan 12, 2018 at 9:16
  • 2
    My original tags were iOS and Swift, I added iOS since that was the tag I usually search for and has always gotten lots of responses with it, and also at that time Swift wasnt Open source and no discussions of opening it. Commented Jan 12, 2018 at 12:55

20 Answers 20

1294

You can use // MARK:


There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than #pragma mark is capable of.

Sign up to request clarification or add additional context in comments.

16 Comments

And yes, the new developer agreement lets us talk about this stuff :)
You cannot use extensions to hold a protocol that has an init method, such as NSCoding. That makes it hard to separate if you can't use it in all cases.
As of beta 4, Xcode 6 recognizes // MARK:, // TODO: and // FIXME in Swift source and lists them in the jump bar. (BTW, it already did in (Obj)C source -- #pragma mark isn't the only way.) And yes, you can still add - to your MARK to put separators in the menu.
+1 for recommending extensions. Even with MARK working now, using extensions to group some kinds of semantically related code (especially protocol implementations) can still be useful. IMHO it reads a lot better to have your declaration of protocol conformance right next to the methods that implement it, not 5 protocol declarations at the top of the file and 50 related method implementations randomly scattered somewhere below.
@StevenKramer: Same way as with #pragma mark. // MARK: - is just a separator, // MARK: - stuff gives you a separator and a header, and // MARK: - stuff - gives you a separator, a header, and another separator all in one comment line.
|
198

Up to Xcode 5 the preprocessor directive #pragma mark existed.

From Xcode 6 on, you have to use // MARK:

These preprocessor features allow to bring some structure to the function drop down box of the source code editor.

some examples :

// MARK:

-> will be preceded by a horizontal divider

// MARK: your text goes here

-> puts 'your text goes here' in bold in the drop down list

// MARK: - your text goes here

-> puts 'your text goes here' in bold in the drop down list, preceded by a horizontal divider

update : added screenshot 'cause some people still seem to have issues with this :

enter image description here

5 Comments

There are no separators in XCode 6.1.1 using // MARK: - text for me and drop down list shows MARK: text instead of just text.
works fine for me in Xcode 6.1.1, I just added a screenshot - please check with your code?
I forgot to mention that I tried it for Objective-C files. Voting up for the effort though, thank you.
I see, now it's clear :-) The initial question asks about Swift so I didn't think of that. For completeness : in Objective-C you can do the same by using : #pragma mark - Your marker text goes here, or just #pragma mark - if you need a bar, or #pragma mark Your marker text goes here to get the same without a bar. (sorry, I cannot get the markup correct for the code fragments, I've put them in bold)
It changed a bit in Xcode 8.1, but this rule are generally working, prefer this answer the best :D
175

For those who are interested in using extensions vs pragma marks (as mentioned in the first comment), here is how to implement it from a Swift Engineer:

import UIKit

class SwiftTableViewController: UITableViewController {

    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

extension SwiftTableViewController {
    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        let cell = tableView?.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell;

        cell.textLabel.text = "Hello World"

        return cell
    }

}

It's also not necessarily the best practice, but this is how you do it if you like.

18 Comments

This is very cool, but it would be nice if extensions could have names.
@Matthew - You could use typealias. For example typealias DataSource = SwiftTableViewController. Then extension Datasource {}
@PhongLe UITableViewController is not a protocol, it is a class. You probably mean UITableViewControllerDataSource, but this is not the pattern used in the example.
I'm just wondering why haven't the extension got the header with the protocol, like extension SwiftTableViewController : UITableViewController, it would be more readable to see why you added that extension to the class.
Note that if your extension exists solely to act as a protocol implementation, you can name the extension: extension SwiftTableViewController : UITableViewDelegate { .. } and extension SwiftTableViewController : UITableViewDatasource { .. }
|
146

Pragma mark - [SOME TEXT HERE] was used in Objective-C to group several function together by line separating.

In Swift you can achieve this using MARK, TODO OR FIXME

i. MARK : //MARK: viewDidLoad

This will create a horizontal line with functions grouped under viewDidLoad(shown in screenshot 1)

Screenshot 1

ii. TODO : //TODO: - viewDidLoad

This will group function under TODO: - viewDidLoad category (shown in screenshot 2)

Screenshot 2

iii. FIXME : //FIXME - viewDidLoad

This will group function under FIXME: - viewDidLoad category (shown in screenshot 3)

Screenshot 3

Check this apple documentation for details.

2 Comments

Notice that the "-" after TODO and FIXME do not do anything. The "-" is only relevant for the MARK directive.
It also creates a large, capitalized section heading in the code "minimap" that you can display along the right side of a source file. Pretty handy.
104

Xcode Official Doc

Apple's current official document section Annotate your code for visibility introduces three comments: TODO:, FIXME:, and MARK:.

Another two comments (though not appearing in the official documentation) supported by latest Xcode version (v14.2): !!!: and ???:.

Note: !!!: and ???: are found to be not supported by some Xcode versions (such as v10.0) for unknown reasons.

Sample screenshot 1 - Xcode 14.2 + macOS 13.1 (Ventura)
Sample screenshot 2 - Xcode 10.1 + macOS 10.14.3 (Mojave)

code_xcode_10_1 jump_bar_xcode_10_1

3 Comments

That was cool, but unfortunately for me using Xcode 12.5 the ??? and !!! annotations aren't doing anything.
@MarkAurelius Xcode v13.3.1 adds back the support to ??? and !!!
The ??? and !!! annotations are still supported in Xcode 14.2
60

In Objective-C code Xcode detects comments like // MARK: - foo which is a bit more portable than #pragma. But these do not seem to be picked up, too (yet?).

Edit: Fixed in Xcode 6 beta 4.

9 Comments

I sure hope they make it available soon because I like to keep everything organized with pragma marks >.<
I can confirm that // MARK: - is not working for the moment.
Not working, but the sample code is littered with that style of comment, so it should be picked up eventually.
is it important the comment should be portable? because porting a Swift code to any other language directly is already challenge for developers.
Hmmm, I see a lot of people commenting that it works, but I'm on Beta 6 and // MARK: doesn't seem to be working. I've tried with & without the space, with and without the colon, all-caps and mixed (Mark). Is there a trick? Do I need to activate a pref or something?
|
40

I think Extensions is a better way instead of #pragma mark.

The Code before using Extensions:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        ...
    }
}

The code after using Extensions:

class ViewController: UIViewController {
    ...
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       ...
    }
}

4 Comments

I think its potential is way much than pragmas but at this time pragmas are still better because extension does not show protocol names or custom names in the drop down menu as pragmas do (see below Whasssaaahhh's answer)
The new "//MARK:" code is useful, but I also like your clear example of how to use extensions — especially for delegate functions!
extensions also limit what you can do - e.g. no stored properties
I use both, because the extension alone does not really stand out in the dropdown menu of Xcode's breadcrumb control.
39

Xcode 8 now handles it as followed and shows up like this in the method dropdown:

enter image description here

5 Comments

what about MARK: ? It shows like // ARK: for me in Xcode 8
Check your code, you might be using some unicode characters above your //MARK: line. For some reason xcode gets confused (and because sucks), and can't handle that.
The !!! and ??? syntax doesn't appear to be working on Xcode 8.3.3...
@ChrisFrederick Even !!! and ??? dosen't seems to be working on Xocde 11.3.1
@JayprakashDubey They don't appear to work in Xcode 12, either…
37

Confirmed with an Apple Engineer in the Swift lab this morning at WWDC that there currently aren't any #pragma or equivalent at the moment, they consider this a bug, and it will arrive soon, so I am guessing beta 2, I hope.

Anyway, it's on it's way.


Xcode now supports //MARK:, //TODO: and //FIXME landmarks to annotate your code and lists them in the jump bar

3 Comments

Beta 2, doesn't have it still
Strange. Works for me just fine. PS: update your Xcode.
@Daniel : Which version of Xcode? I'm using Xcode 6.4 and seems not working on it.
23

There are Three options to add #pragma_mark in Swift:

1) // MARK: - your text here -

2) // TODO: - your text here -

3) // FIXME: - your text here -

Note: Uses - for add separators

Comments

18

Use

// MARK: SectionName

or

// MARK: - SectionName

This will give a line above pragma mark, making it more readable.

For ease just add

// MARK: - <#label#>

to your code snippets.

Alternate way -

Use it in this way

private typealias SectionName = ViewController
private extension SectionName  {
    // Your methods
}

This will not only add mark(just like pragma mark) but also segregate the code nicely.

2 Comments

If you use Swiftlint, it will complain about the //MARK format (no space) and suggest // MARK: (text) (one space between // and MARK, no space between MARK and :, and one space between : and the section name)
@NicolasMiari, Thanks, I have edited according to your suggestion. And will also try using SwiftLint for next project. :)
16

You may also be interested in Swift 4.2 / XCode 10 compiler directives like

#warning("Some string to display")

and

#error("Some error to display")

It might be useful when you really don't want to miss something.

enter image description here

1 Comment

Cool. I will warn other teammates when the violate boy scout rule onwards.
15
//# MARK: - Spinner Class Methods

Add a line between the colon and your description to insert a separator line. This helps to organize your code even more. The code and screenshot above make use of the MARK comment with a line included.

  1. //# MARK: – Text Methods (LINE)
  2. //# MARK: Text Methods (NO LINE)

This only works with the MARK comment.

enter image description here

Comments

12

Professional programer must be use this tag for good code. It is also good for team work.

// MARK: example Web Service start here
// TODO: example 1
// FIXME: Please change BASE url before live 

It is easy to find method like this

It is easy to find method like this

Comments

12

In Xcode 11 they added minimap which can be activated Editor -> Minimap.

Minimap will show each mark text for fast orientation in code. Each mark is written like // MARK: Variables

enter image description here

Comments

5

//MARK: does not seem to work for me in Xcode 6.3.2. However, this is what I did to get it to work:

1) Code:

import Cocoa

class MainWindowController: NSWindowController {

    //MARK: - My cool methods

    func fly() {
    }

    func turnInvisible() {

    }
}

2) In the jump bar nothing appears to change when adding the //MARK: comment. However, if I click on the rightmost name in the jump bar, in my case it says MainWindowController(with a leading C icon), then a popup window will display showing the effects of the //MARK: comment, namely a heading that says "My cool methods":

enter image description here

3) I also notice that if I click on one of the methods in my code, then the method becomes the rightmost entry in the jump bar. In order to get MainWindowController(with a leading C icon) to be the rightmost entry in the jump bar, I have to click on the whitespace above my methods.

1 Comment

Isnt that how its supposed to be? That you have to click the top bar?
4

Apple states in the latest version of Building Cocoa Apps,

The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.

The # character appears to still be how you work with various build configurations and things like that, but it looks like they're trying to cut back on your need for most preprocessing in the vein of pragma and forward you to other language features altogether. Perhaps this is to aid in the operation of the Playgrounds and the REPL behaving as close as possible to the fully compiled code.

Comments

2

Pragma mark is a way to improve the readability of your code. The pragma comments would appear like tags on the Xcode jumpbar.

//MARK:  <Your comment goes here>

Example: In the code,

//MARK: Properties

// MARK: View Life cycle

//MARK: Helper methods

This is how it would appear in the Xcode jump bar.

enter image description here

1 Comment

You just have to insert them at the correct places in your file.
1

Add a to-do item: Insert a comment with the prefix TODO:. For example: // TODO: [your to-do item].

Add a bug fix reminder: Insert a comment with the prefix FIXME:. For example: // FIXME: [your bug fix reminder].

Add a heading: Insert a comment with the prefix MARK:. For example: // MARK: [your section heading].

Add a separator line: To add a separator above an annotation, add a hyphen (-) before the comment portion of the annotation. For example: // MARK: - [your content]. To add a separator below an annotation, add a hyphen (-) after the comment portion of the annotation. For example: // MARK: [your content] -.

Comments

1

Try this:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.