1013

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?

rolling_codes
  • 15,174
  • 22
  • 76
  • 112
Arbitur
  • 38,684
  • 22
  • 91
  • 128
  • 25
    It's really important for organize our long code. – iPatel Jun 03 '14 at 14:21
  • It appears there is no longer a quickly visible difference between comments and section-markings. Extensions are not named, so separate files seem to be the only way to delineate between the two types of comments – Stephen J Aug 19 '15 at 23:23
  • 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. – RenniePet Jan 21 '17 at 01:00
  • @harshil-kotecha "iOS" is *not* a good keyword for this question. Swift works on iOS, macOS, tvOS, watchOS, and even Linux. Questions about Swift such as this one are not specifically questions about iOS at all. – Eric Aya Jan 11 '18 at 13:55
  • 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 . – Harshil Kotecha Jan 12 '18 at 05: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. – Eric Aya Jan 12 '18 at 09: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. – Arbitur Jan 12 '18 at 12:55

20 Answers20

1287

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.

joshuakcockrell
  • 5,200
  • 2
  • 34
  • 47
Frank Schmitt
  • 25,648
  • 10
  • 58
  • 70
  • 69
    And yes, the new developer agreement lets us talk about this stuff :) – Frank Schmitt Jun 04 '14 at 12:47
  • 5
    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. – Matthew Knippen Jun 07 '14 at 00:09
  • Will making liberal use of class extensions hurt performance at all? – ma11hew28 Jul 02 '14 at 15:58
  • 160
    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. – rickster Jul 21 '14 at 17:24
  • 17
    +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. – rickster Jul 21 '14 at 17:27
  • I really liked the suggestion of using class extensions, but in no way is such a "better practice" since #pragma mark (and now //MARK:) is a much more general capability and is rendered in bold face in Xcode's selector pull down. – ctpenrose Oct 20 '14 at 23:31
  • @rickster How do you get the separator in a // MARK:? I can't seem to find the syntax for that. – Steven Kramer Jan 14 '15 at 10:09
  • 41
    @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. – rickster Jan 14 '15 at 16:56
  • Okay thanks, the separators must be Swift only then. – Steven Kramer Jan 15 '15 at 00:08
  • 3
    FWIW, Apple's docs on Adding Protocol Conformance with an Extension: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID469 – qix Mar 11 '15 at 00:12
  • 1
    This is what I like to add to the snippets. Add a snippet titled "Pragma Mark", with the shortcut "mark" and contents // MARK: <#Your Pragma Mark#>. Then, simply type "mark" and enter on the pop up suggestion, I think you will like the results. – Jay Imerman Oct 07 '15 at 19:29
  • As a sidenote, on Xcode 7.3, you have to use marks in their own lines. For example (at least for Objective-C), if you write `[someObject someMethod]; // MARK: Some marking text` the mark will be ignored, but if you write `// MARK: Some marking text` in an empty line, it will work fine. – Alejandro Iván Jul 14 '16 at 14:43
  • 1
    To add some more relevance given Xcode's recent update to Xcode 11, `//MARK:` and `//MARK:-` both show up really nicely on the new minimap feature. Try it out! (CNTRL+SHIFT+CMD+M) – Xavier L. Oct 23 '19 at 09:08
  • As of Xcode 11, you can now use `// MARK:` in Objective-C code. Yay! – RndmTsk Apr 22 '20 at 18:32
  • As long as `Swift` does not allow `override` keyword for `protocol` implementations, it does not matter if we use comment or extension, things break silently if any optional-member of protocol changes. – Top-Master Sep 12 '22 at 19:11
  • Swift is decades behind C++ and Java's inheritance, for example, because not allowing override keyword for protocol implementations (even if protocol-member is optional). – Top-Master Sep 12 '22 at 19:15
197

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

Ky -
  • 30,724
  • 51
  • 192
  • 308
Ronny Webers
  • 5,244
  • 4
  • 28
  • 24
  • 1
    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**. – mostruash Feb 21 '15 at 15:08
  • works fine for me in Xcode 6.1.1, I just added a screenshot - please check with your code? – Ronny Webers Feb 22 '15 at 17:51
  • I forgot to mention that I tried it for Objective-C files. Voting up for the effort though, thank you. – mostruash Feb 23 '15 at 13:16
  • 2
    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) – Ronny Webers Feb 24 '15 at 21:36
  • It changed a bit in Xcode 8.1, but this rule are generally working, prefer this answer the best :D – windsound Nov 30 '16 at 02:56
177

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.

NatashaTheRobot
  • 6,879
  • 4
  • 32
  • 27
  • 6
    This is very cool, but it would be nice if extensions could have names. – Matthew Knippen Jun 06 '14 at 23:40
  • The other issue with this is it won't work for all protocols, such as NSCoding. init methods cannot go inside extensions. – Matthew Knippen Jun 07 '14 at 00:08
  • 17
    @Matthew - You could use `typealias`. For example `typealias DataSource = SwiftTableViewController`. Then `extension Datasource {}` – Logan Jun 08 '14 at 18:40
  • Would it have been cleaner to add the protocol to the extension? Like this `extension SwiftTableViewController: UITableViewController` – Phong Le Jun 12 '14 at 18:36
  • 1
    @PhongLe `UITableViewController` is not a protocol, it is a class. You probably mean `UITableViewControllerDataSource`, but this is not the pattern used in the example. – KPM Jun 14 '14 at 12:02
  • @KPM oops your right, thought it was a view controller with a uitableview add. – Phong Le Jun 14 '14 at 19:37
  • 4
    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. – holex Jun 16 '14 at 08:45
  • 1
    But still it does not show up in the [method navigation menu](http://i.stack.imgur.com/XFIBX.png) like #pragma mark used to separate the menu items. – GoodSp33d Jun 17 '14 at 11:45
  • 1
    @GoodSp33d I'm assuming the benefit of doing it in this way is that then you can have seperate files to organize your code in then just declare extensions in those files. So I may have `MyViewControllerDatasource.swift` and in there have an extension with everything relating to datasource...at least that's how I'm organizing my code. – Literphor Jun 19 '14 at 05:06
  • @Literphor Didnt know that :) Thats really helpful in organizing code. I remember some of the singleton classes running upto ~2k lines of code. – GoodSp33d Jun 19 '14 at 09:20
  • If the base was UIViewController, I like it. Otherwise we're already coupled. But then it's just semantics, really, and it sure makes deleting deleting "grouped" code more obvious than with pragmas! – Alex the Ukrainian Jun 24 '14 at 21:05
  • Hi, just curiosity, who is this engineer and where did you read this from? Thanks. – Unheilig Jun 28 '14 at 19:24
  • Why is it not best practice? Does making liberal use of class extensions hurt performance at all? – ma11hew28 Jul 02 '14 at 16:00
  • @Unheilig I asked about this at the Swift lab during WWDC14 - don't remember the name of the Engineer. – NatashaTheRobot Jul 04 '14 at 18:55
  • @MattDiPasquale just saying I don't know whether this is best practice or not, since there are other ways to accomplish this same thing, such as creating a data source object (subclass of NSObject) for example, and setting it as your tableview's data source. Haven't heard anything about class extensions hurting performance. – NatashaTheRobot Jul 04 '14 at 18:59
  • 7
    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 { .. }` – Craig Otis Jul 30 '14 at 12:13
  • I like using the class extensions (a nice way of grouping the code), *and* the // MARK: style, for differentiation in the pull down. – coco Dec 26 '14 at 21:11
  • so if you have to make many MARK, then will you be able to make many extensions like this – rd_ May 14 '16 at 02:01
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.

Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177
  • Notice that the "-" after TODO and FIXME do not do anything. The "-" is only relevant for the MARK directive. – rismay Feb 02 '16 at 22:41
  • 1
    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. – Oscar May 15 '20 at 23:53
98

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

George
  • 3,384
  • 5
  • 40
  • 64
61

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.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • 6
    I sure hope they make it available soon because I like to keep everything organized with pragma marks >. – Arbitur Jun 03 '14 at 14:18
  • 1
    I can confirm that `// MARK: -` is not working for the moment. – Rui Peres Jun 03 '14 at 14:30
  • Not working, but the sample code is littered with that style of comment, so it should be picked up eventually. – Nate Cook Jun 03 '14 at 14:51
  • 1
    is it important the comment should be portable? because porting a _Swift_ code to any other language directly is already challenge for developers. – holex Jun 16 '14 at 08:48
  • 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? – Olie Aug 24 '14 at 15:23
  • @Olie You forgot the dash. – Nikolai Ruhe Aug 25 '14 at 06:53
  • @Nikolai: in my code, I have the dash, though I was under the impression that it is not needed. From #pragma, the dash just adds the separator to the menu. I was under the impression that the key here was `MARK:`, similar to `FIXME:` or `TODO:` – Olie Aug 25 '14 at 14:25
  • @Olie You are right, of course. I'm seeing the separator and the caption in my Xcode, though. – Nikolai Ruhe Aug 25 '14 at 14:42
  • Right. Everybody else is seeing it. That's why I was asking if there's some weird config or setup or spelling or other thing that makes it not-show. Can't attach an image to a comment, but I'm pretty fluent with iOS, XCode, etc., and I don't think it's a "stupid user mistake." (Heh. The key to finding your stupid user mistake is to publish in a public forum that you're certain it's not! ;) ) – Olie Aug 25 '14 at 19:54
41

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) {
       ...
    }
}
jqgsninimo
  • 6,562
  • 1
  • 36
  • 30
  • 6
    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](http://stackoverflow.com/a/26408706/149008)) – nacho4d Feb 26 '15 at 02:44
  • The new "//MARK:" code is useful, but I also like your clear example of how to use extensions — especially for delegate functions! – ElmerCat Nov 24 '15 at 01:04
  • extensions also limit what you can do - e.g. no stored properties – Confused Vorlon Feb 07 '17 at 14:46
  • 1
    I use both, because the `extension` alone does not really stand out in the dropdown menu of Xcode's breadcrumb control. – Nicolas Miari Oct 30 '17 at 10:27
40

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

enter image description here

Antoine
  • 23,526
  • 11
  • 88
  • 94
38

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

Daniel
  • 23,129
  • 12
  • 109
  • 154
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

Berlin
  • 2,115
  • 2
  • 16
  • 28
19

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.

Nikhil Manapure
  • 3,748
  • 2
  • 30
  • 55
  • 1
    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) – Nicolas Miari Oct 30 '17 at 10:25
  • 2
    @NicolasMiari, Thanks, I have edited according to your suggestion. And will also try using SwiftLint for next project. :) – Nikhil Manapure Oct 30 '17 at 10:42
17
//# 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

aashish tamsya
  • 4,903
  • 3
  • 23
  • 34
17

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

fewlinesofcode
  • 3,007
  • 1
  • 13
  • 30
13

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

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
Harshil Kotecha
  • 2,846
  • 4
  • 27
  • 41
13

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

MarekB
  • 612
  • 6
  • 12
7

//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.

7stud
  • 46,922
  • 14
  • 101
  • 127
5

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.

UtopiaLtd
  • 2,520
  • 1
  • 30
  • 46
3

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

vrat2801
  • 538
  • 2
  • 13
2

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] -.

casillas
  • 16,351
  • 19
  • 115
  • 215
Hiren
  • 689
  • 6
  • 12
2

Try this:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}
Zouhair Sassi
  • 1,403
  • 1
  • 13
  • 30
Nirbhay Singh
  • 1,204
  • 1
  • 12
  • 16