Code Formatting In Xcode

Viewed 31947

Is there anyway to format the code in Xcode like you can do in Eclipse or Netbenas. I have not found any option in menu, is there any hot key for this or its simply not in Xcode?

11 Answers

Well, first of all welcome to 2021. I know it's a very old question but still people like me visit this and for those people, I'm putting out multiple available solutions in one answer that worked for me after 2 hours of research and testing.

Re-Indent

As everyone else is suggesting, it's one of the default solution if you just want to re-indent the lines of code:

Goto: Editor -> Structure -> Re-Indent or use shortcut control + I

Using Xcode Extensions

There are 2 extensions I found and used which works charmingly for me.

1) SwiftFormat: mentioning the steps to install the xcode extension here from the readme.

Like the command-line tool, you can install the SwiftFormat for Xcode extension application via Homebrew. Assuming you already have Homebrew installed, type:

$ brew install --cask swiftformat-for-xcode

  • open the SwiftFormat for Xcode.app that you just installed. there you can change the rules of formatting.

  • After that, open the system preference -> extensions -> xcode source editor and mark the checkbox for SwiftFormat.

  • Restart the Xcode

Voila! You're good to go. you can use three options. format selected code, format entire file OR just lint file.

2) Swimat: (it is already mentioned in one of the answer here by @Guy Daher) steps to install from readme

Install via homebrew-cask

Homebrew latest version

brew install --cask swimat

  • Similar to above extension installation, open the Swimat.app if it does not open then try to sove it from system preferences -> security & privacy -> open swimat app

  • after opening, click on install in ./bin folder to make it work globally (not sure about this step but I just did it)

  • Restart Xcode

now you can goto editor -> swimat -> format

Bingo! You're good to go.

Additional uninvited help

You can simply set the keybinding to use any of this command. i.e. I've set the android studio default command to reformat the code as option + command + L

ps If anyone else found a better extension, please let me know in comment, I'll add it to the list.

^-I (control - capital i) : format the current line

-A + ^-I : format the whole code file

Try this solution: ⌘A [⌘K ⌘F]

enter image description here

Related