skip to Main Content

I started a new iOS project in Xcode with SwiftUI and I want to install swift-format to format the code as I work on the app. Unfortunately, it seems harder then I anticipated.

The library: https://github.com/apple/swift-format

I added swift-format package using Xcode, like this: File -> Swift Packages -> Add Package Dependency....

And I have no idea why the executable is disabled:

add package dependency from xcode

Anyways, after selecting the first two options (SwiftFormat and SwiftFormatConfiguration) I don’t know how to use this library in order to format the code…

My question is, how I can run this library so that it formats the files for me?

2

Answers


  1. You can use XCFormat. It is Xcode extension that you will find in the App Store. I think it is free. Then, you can access it through the editor menu in Xcode. Of course, you can also create a shortcut and simply use your keyboard for added convenience.

    Login or Signup to reply.
  2. I made it work via Quick Actions and shortcut to format current document in Xcode with swift-format.

    1. Follow instructions from https://github.com/apple/swift-format to build the library
    2. Place swift-format binary to the global path… I did it with symlink ln -s /path/to/your/binary/swift-format /usr/local/bin/swift-format
    3. Open Automator and create new Quick Action (name it with recognizable name like xcode-swift-format) and add the following Apple script to the action:
    set current_document_path to ""
    
    tell application "Xcode"
        set last_word_in_main_window to (word -1 of (get name of window 1))
        if (last_word_in_main_window is "Edited") then
            tell application "System Events" to keystroke "s" using command down
            delay 1
        end if
        set last_word_in_main_window to (word -1 of (get name of window 1))
        set current_document to document 1 whose name ends with last_word_in_main_window
        set current_document_path to path of current_document
    end tell
    if (current_document_path is not "") then
        do shell script "/usr/local/bin/swift-format format -i " & current_document_path
    end if
    
    1. Set shortcut in System Preferences -> Keyboard -> Shortcuts -> Services for your quick action:
      System preferences shortcut

    2. Add Xcode to System Preferences -> Security & Privacy -> Privaciy -> Accessibility (This step is needed so script can send Command+S keystroke to Xcode if you try to format unsaved document, it means it will save document before formatting)
      Xcode to Accessibility

    1. Edit your.swift file in Xcode and hit the shortcut in my case Alt+Command+= … it takes a second or two for the doc to be formatted.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search