xcodeindentationshortcutcurly-braceskeystroke

Enclose code in braces and indent automatically in Xcode?


Is there any convenient way to do all these things at once in Xcode?
Take a selected block of text and enclose it in a set of curly braces, each on their own line, with proper indentation like this:

Before:

    idea.ponder()
    doSomething()

After selecting the 2 lines and hitting a shortcut:

    {
        idea.ponder()
        doSomething()
    }

… preferably with the cursor positioned just before the opening brace.

That way I could just, for instance, type withAnimation or DispatchQueue.main.async or if !tooSleepy and be on my way.

I find myself doing this sort of thing manually so often, and I've never seen a convenient Xcode shortcut. (Though there are shortcuts for indenting, for wrapping in braces without adding newlines, etc.) Am I missing something?

thanks!


Solution

  • On my machine, selecting the lines and typing a left curly brace does exactly what you just said. Example:

    self.contentView.layer.cornerRadius = 8
    self.contentView.backgroundColor = .blue
    

    I select both lines (triple-click-and-drag) and hit { key, and I get

    {
        self.contentView.layer.cornerRadius = 8
        self.contentView.backgroundColor = .blue
    }
    

    To get the cursor before the first curly brace, choose Editor > Selection > Balance Delimiters (you can give that a shortcut) and then left-arrow.

    enter image description here

    An alternative approach might be: select and cut the lines, use code completion to insert the desired construct, then paste the lines back in.

    enter image description here