Emacs: swift-mode package

This article will describe using swift package which provides major mode for swift.

1 Install swift-mode package

Install swift-mode package with M-x package-list-packages.

swift-mode  0.3.0  installed  Major-mode for Apple's Swift programming language.

2 Install quickrun package

Install quickrun package with M-x package-list-packages. This is used for running swift.

quickrun  2.2.5  installed  Run commands quickly

3 Install flycheck package

Install flycheck package with M-x package-list-packages

flycheck  0.24  installed  On-the-fly syntax checking

4 ${HOME}/.emacs

The default values of custom variables are as below. swift-repl-executable is command for running swift.

swift-indent-offset 4
swift-indent-switch-case-offset 0
swift-indent-multiline-statement-offset 2
swift-repl-executable "xcrun swift"

This article set tab width to as below.

(custom-set-variables
 '(swift-indent-offset 2)
 '(swift-indent-multiline-statement-offset 1)
)

Add quickrun keybindings to swift-mode-hook.

(add-hook 'swift-mode-hook
  '(lambda()
    (local-set-key "\C-c\C-c" 'quickrun)
    (local-set-key "\C-c\C-a" 'quickrun-with-arg)
  )
)

Add global-flycheck-mode to after-init-hook.

(add-hook 'after-init-hook #'global-flycheck-mode)

Add swift to flychecker-checkers when swift-mode-hook is enabled. Set swift SDK path to flycheck-swift-sdk-path.

(add-hook 'swift-mode-hook
  '(lambda()
     (add-to-list 'flycheck-checkers 'swift)
     (setq flycheck-swift-sdk-path
       (replace-regexp-in-string
        "\n+$" "" (shell-command-to-string
                   "xcrun --show-sdk-path --sdk macosx")))
  )
)

5 Run swift-mode

Open *.swift or run M-x swift-mode.

6 Key bindings

Key bindings for swift-mode is as below.

C-c C-z Run swift in shell
C-c C-f Run swift in buffer
C-c C-r Run swift to selected region

Key bindings for quickrun is as below.

C-c C-c Run swift in buffer
C-c C-a Run swift in buffer with argument

7 Execution result

Running swift-mode is as below.

0001_Swift-Highlight.png