Search code examples
xcodeautoformatting

Auto-formatting Swift in Xcode for a blind developer


The answers to How to use code formatter in Xcode for Swift? suggest that Xcode has the ability to auto-format swift code and that the feature can be invoked using +I (Ctrl-I)

When I try it on the following Swift function absolutely nothing changes

func displayGuesses(){
    replaceWord = ""
    for character in chosenWord!{
        if guesses.contains(String(character)) {
            replaceWord.append(character)
        }
        else{
            replaceWord.append("_")
        }
            }

    guessLabel.text = replaceWord
}

I would expect it to align the curly-brace closing the for loop with the opening statement.

Is there a feature in Xcode that would correctly format this Swift function? How do I invoke it from the keyboard?

Note that this is not about selecting the code first. If I select the whole file first—using +A (Cmd-A)—then there is still no effect.

(N.B. You may wonder why I am writing oddly formatted code. I'm working with a blind kid who is swapping from Python on the PC to Swift on a Mac. Python uses indentation for scoping. I was excited to teach him Swift as he would not have to worry so much about indentation. But, if he wants to share code with sighted developers, then it would be handy if Xcode would tidy up the formatting for him.)


Solution

  • If the keyboard shortcut for formatting is still in its default state, formatting the code should be achieved by selecting all of the code +A or clicking inside the function that you want to format and then you can click +I.

    Another way:

    Menu > Editor > Structure > Re-Indent

    enter image description here

    If +I is not showing in the menu next to Re-Indent, that means that the default keyboard shortcut was changed.

    In order to fix it, go to:

    Xcode > Preferences > Key Bindings > Search for Re-Indent and change it back to default.

    enter image description here