By Arbitur


2014-06-03 14:05:56 8 Comments

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?

19 comments

@varunrathi28 2019-05-23 13:53:58

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

@varunrathi28 2019-07-21 19:04:06

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

@Nirbhay Singh 2019-04-20 17:59:52

Try this:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}

@Harshil Kotecha 2017-07-06 05:12:59

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

@George 2018-05-03 10:26:52

Official Documentation

Apple's official document about Xcode Jump Bar: Add code annotations to the jump bar

Jump Bar Screenshots for Sample Code

Sample Code

Behavior in Xcode 10.1 and macOS 10.14.3 (Mojave)

Xcode 10.1 and macOS 10.14.3

Behavior in Xcode 10.0 and macOS 10.13.4 (High Sierra)

Xcode 10.0 and macOS 10.13.4

Behavior in Xcode 9.4.1 and macOS 10.13.0

Xcode 9.4.1 and macOS 10.13.0

Discussion

!!!: and ???: sometimes are not able to be displayed.

@Hiren 2018-09-08 15:29:07

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

@fewlinesofcode 2018-10-16 20:30:37

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

@Arbitur 2018-10-16 21:46:03

That's cool didnt know about those

@Sazzad Hissain Khan 2019-05-21 13:56:39

Cool. I will warn other teammates when the violate boy scout rule onwards.

@Frank Schmitt 2014-06-04 12:46:48

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.

@Frank Schmitt 2014-06-04 12:47:41

And yes, the new developer agreement lets us talk about this stuff :)

@Matthew Knippen 2014-06-07 00:09:08

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.

@ma11hew28 2014-07-02 15:58:32

Will making liberal use of class extensions hurt performance at all?

@rickster 2014-07-21 17:24:18

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 2014-07-21 17:27:51

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

@Juan Carlos Méndez 2014-10-03 14:51:13

@MattDiPasquale - no performance impact

@ctpenrose 2014-10-20 23:31:51

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.

@Steven Kramer 2015-01-14 10:09:00

@rickster How do you get the separator in a // MARK:? I can't seem to find the syntax for that.

@rickster 2015-01-14 16:56:53

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

@Steven Kramer 2015-01-15 00:08:21

Okay thanks, the separators must be Swift only then.

@qix 2015-03-11 00:12:35

FWIW, Apple's docs on Adding Protocol Conformance with an Extension: developer.apple.com/library/ios/documentation/Swift/Conceptu‌​al/…

@Jay Imerman 2015-10-07 19:29:57

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.

@cat 2016-02-17 01:01:34

"the new developer agreement lets us talk about this stuff" -- it's almost as if you build nukes, not software

@Chamath Jeevan 2016-03-17 05:13:23

This feature is implemented since Xcode 7.2

@Alejandro Iván 2016-07-14 14:43:14

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.

@ssowri1 2017-10-24 13:50:33

Thank you for your explanation.

@Jaydip 2017-09-30 08:53:20

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

@Nikhil Manapure 2016-11-21 10:54:34

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.

@Nicolas Miari 2017-10-30 10:25:14

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)

@Nikhil Manapure 2017-10-30 10:42:49

@NicolasMiari, Thanks, I have edited according to your suggestion. And will also try using SwiftLint for next project. :)

@jqgsninimo 2014-06-30 09:05:21

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) {
       ...
    }
}

@nacho4d 2015-02-26 02:44:46

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)

@ElmerCat 2015-11-24 01:04:20

The new "//MARK:" code is useful, but I also like your clear example of how to use extensions — especially for delegate functions!

@Confused Vorlon 2017-02-07 14:46:22

extensions also limit what you can do - e.g. no stored properties

@Nicolas Miari 2017-10-30 10:27:01

I use both, because the extension alone does not really stand out in the dropdown menu of Xcode's breadcrumb control.

@Antoine 2016-06-17 00:25:35

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

enter image description here

@fnc12 2016-09-15 10:40:32

what about MARK: ? It shows like // ARK: for me in Xcode 8

@carlos_ms 2017-01-06 14:48:56

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.

@Chris Frederick 2017-06-12 06:33:05

The !!! and ??? syntax doesn't appear to be working on Xcode 8.3.3...

@aashish tamsya 2016-02-29 09:35:11

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

@Jayprakash Dubey 2015-10-09 13:52:59

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

@Vakas 2015-10-28 06:21:10

Thanks, This works for XCode 7 and Swift 2.0

@rismay 2016-02-02 22:41:24

Notice that the "-" after TODO and FIXME do not do anything. The "-" is only relevant for the MARK directive.

@7stud 2015-07-03 04:42:47

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

@Arbitur 2015-07-03 06:57:03

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

@Ronny Webers 2014-10-16 15:49:36

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

@mostruash 2015-02-21 15:08:18

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.

@Ronny Webers 2015-02-22 17:51:55

works fine for me in Xcode 6.1.1, I just added a screenshot - please check with your code?

@mostruash 2015-02-23 13:16:56

I forgot to mention that I tried it for Objective-C files. Voting up for the effort though, thank you.

@Ronny Webers 2015-02-24 21:36:29

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)

@windsound 2016-11-30 02:56:23

It changed a bit in Xcode 8.1, but this rule are generally working, prefer this answer the best :D

@Nikolai Ruhe 2014-06-03 14:12:42

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.

@Arbitur 2014-06-03 14:18:38

I sure hope they make it available soon because I like to keep everything organized with pragma marks >.<

@Rui Peres 2014-06-03 14:30:47

I can confirm that // MARK: - is not working for the moment.

@Arbitur 2014-06-03 14:36:11

@JackyBoy Yea I tried it too :(

@Nate Cook 2014-06-03 14:51:08

Not working, but the sample code is littered with that style of comment, so it should be picked up eventually.

@Adam Waite 2014-06-10 12:51:27

It works in Apple's sample Lister app

@holex 2014-06-16 08:48:08

is it important the comment should be portable? because porting a Swift code to any other language directly is already challenge for developers.

@Olie 2014-08-24 15:23:13

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?

@Nikolai Ruhe 2014-08-25 06:53:33

@Olie You forgot the dash.

@Olie 2014-08-25 14:25:46

@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:

@Nikolai Ruhe 2014-08-25 14:42:22

@Olie You are right, of course. I'm seeing the separator and the caption in my Xcode, though.

@Olie 2014-08-25 19:54:54

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! ;) )

@Daniel 2014-06-06 21:58:30

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

@cescofry 2014-06-22 13:02:28

Beta 2, doesn't have it still

@Arbitur 2014-07-21 22:06:58

In xcode beta 3?

@Daniel 2014-07-22 12:41:02

Beta 4 has it now.

@7stud 2015-07-03 04:37:13

None of the three comments works in Xcode 6.3.2

@Daniel 2015-07-03 08:36:12

Strange. Works for me just fine. PS: update your Xcode.

@Jayprakash Dubey 2015-10-09 12:23:50

@Daniel : Which version of Xcode? I'm using Xcode 6.4 and seems not working on it.

@NatashaTheRobot 2014-06-05 20:00:13

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.

@Matthew Knippen 2014-06-06 23:40:31

This is very cool, but it would be nice if extensions could have names.

@Matthew Knippen 2014-06-07 00:08:04

The other issue with this is it won't work for all protocols, such as NSCoding. init methods cannot go inside extensions.

@Logan 2014-06-08 18:40:22

@Matthew - You could use typealias. For example typealias DataSource = SwiftTableViewController. Then extension Datasource {}

@Phong Le 2014-06-12 18:36:29

Would it have been cleaner to add the protocol to the extension? Like this extension SwiftTableViewController: UITableViewController

@KPM 2014-06-14 12:02:09

@PhongLe UITableViewController is not a protocol, it is a class. You probably mean UITableViewControllerDataSource, but this is not the pattern used in the example.

@Phong Le 2014-06-14 19:37:51

@KPM oops your right, thought it was a view controller with a uitableview add.

@holex 2014-06-16 08:45:07

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.

@GoodSp33d 2014-06-17 11:45:34

But still it does not show up in the method navigation menu like #pragma mark used to separate the menu items.

@Literphor 2014-06-19 05:06:24

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

@GoodSp33d 2014-06-19 09:20:02

@Literphor Didnt know that :) Thats really helpful in organizing code. I remember some of the singleton classes running upto ~2k lines of code.

@Alex the Ukrainian 2014-06-24 21:05:22

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!

@Unheilig 2014-06-28 19:24:30

Hi, just curiosity, who is this engineer and where did you read this from? Thanks.

@ma11hew28 2014-07-02 16:00:35

Why is it not best practice? Does making liberal use of class extensions hurt performance at all?

@NatashaTheRobot 2014-07-04 18:55:10

@Unheilig I asked about this at the Swift lab during WWDC14 - don't remember the name of the Engineer.

@NatashaTheRobot 2014-07-04 18:59:59

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

@Craig Otis 2014-07-30 12:13:07

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 { .. }

@coco 2014-12-26 21:11:25

I like using the class extensions (a nice way of grouping the code), and the // MARK: style, for differentiation in the pull down.

@rd_ 2016-05-14 02:01:45

so if you have to make many MARK, then will you be able to make many extensions like this

@NatashaTheRobot 2016-05-15 12:26:31

I wrote a detailed blog post on how I use extensions this way in Swift: natashatherobot.com/using-swift-extensions

@Pranav Kasetti 2018-12-04 20:59:23

numberOfSectionsInTableView doesn't need to be declared as the default value is already 1.

@UtopiaLtd 2014-06-03 14:19:49

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.

Related Questions

Sponsored Content

17 Answered Questions

[SOLVED] How do I call Objective-C code from Swift?

  • 2014-06-02 20:05:42
  • David Mulder
  • 267954 View
  • 919 Score
  • 17 Answer
  • Tags:   objective-c swift

24 Answered Questions

[SOLVED] Can't use Swift classes inside Objective-C

31 Answered Questions

[SOLVED] Swift to Objective-C header not created in Xcode 6

16 Answered Questions

[SOLVED] #ifdef replacement in the Swift language

9 Answered Questions

[SOLVED] Swift Beta performance: sorting arrays

14 Answered Questions

[SOLVED] Swift: #warning equivalent

  • 2014-06-12 11:58:27
  • SomeGuy
  • 40508 View
  • 186 Score
  • 14 Answer
  • Tags:   swift

19 Answered Questions

[SOLVED] Xcode 8 Beta 3 Use Legacy Swift issue

22 Answered Questions

[SOLVED] What does an exclamation mark mean in the Swift language?

1 Answered Questions

[SOLVED] Pragma mark in swift

2 Answered Questions

Sponsored Content