繁体   English   中英

如何将 Apple 的 swift-format 与 Xcode 一起使用?

[英]How to use Apple's swift-format with Xcode?

我使用 SwiftUI 在 Xcode 中启动了一个新的 iOS 项目,并且我想安装swift-format以在我在应用程序上工作时格式化代码。 不幸的是,这似乎比我预期的要难。

图书馆: https://github.com/apple/swift-format

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

而且我不知道为什么禁用可执行文件:

从 xcode 添加包依赖项

无论如何,在选择前两个选项( SwiftFormatSwiftFormatConfiguration )后,我不知道如何使用这个库来格式化代码......

我的问题是,我如何运行这个库以便它为我格式化文件?

您可以使用 XCFormat。 它是您可以在 App Store 中找到的 Xcode 扩展。 我认为它是免费的。 然后,您可以通过 Xcode 中的编辑器菜单访问它。 当然,您也可以创建快捷方式并简单地使用键盘来增加便利性。

我通过快速操作和快捷方式使其工作,以使用swift-format Xcode 中的当前文档。

  1. 按照https://github.com/apple/swift-format的说明构建库
  2. 将 swift-format 二进制文件放置到全局路径中...我使用符号链接ln -s /path/to/your/binary/swift-format /usr/local/bin/swift-format
  3. 打开 Automator 并创建新的快速操作(使用可识别的名称命名,例如xcode-swift-format )并将以下 Apple 脚本添加到操作中:
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. 在系统偏好设置 -> 键盘 -> 快捷方式 -> 服务中设置快捷方式以进行快速操作: 系统偏好设置快捷方式

  2. 将 Xcode 添加到 System Preferences -> Security & Privacy -> Privaciy -> Accessibility (需要此步骤,以便脚本可以将 Command+S 击键发送到 Xcode 如果您尝试格式化未保存的文档,这意味着它将在格式化之前保存文档) Xcode 到可访问性

  1. 在 Xcode 中编辑your.swift文件,然后在我的情况下点击快捷方式Alt+Command+= ... 格式化文档需要一两秒钟。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM