查看: 62|回复: 0

给Xcode使用完整版本的swiftformat

[复制链接]

2

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2011-11-21
发表于 2026-3-25 11:09:00 | 显示全部楼层 |阅读模式
  • 给Xcode使用完整版本的swiftformat
    • 脚本配置
    • 导入到Xcode
    • 快捷键设置

脚本配置

现在最新的Xcode有集成到swiftformat,但是因为集成的不好实时更新、执行外部config,所以还是做个自动脚本来执行终端的swiftformat

-- ===== 个人配置,使用前请修改 =====
set swiftformatPath to "/opt/homebrew/bin/swiftformat"
set configPath to "~/Desktop/id.swiftformat"
-- ==================================

tell application "Xcode"
    set projPath to path of document of window 1
    set projDir to do shell script "dirname " & quoted form of projPath
end tell

tell application "System Events"
    tell process "Xcode"
        set windowTitle to name of window 1
    end tell
end tell

if windowTitle does not contain " — " then
    display dialog "无法识别当前窗口,请确保 Xcode 中有文件打开。" buttons {"OK"} default button "OK" with icon stop
    return
end if

set AppleScript's text item delimiters to " — "
set titleParts to text items of windowTitle
set AppleScript's text item delimiters to ""

set fileName to text item 2 of titleParts
if fileName does not end with ".swift" then
    display dialog "当前文件不是 .swift 文件:" & fileName buttons {"OK"} default button "OK" with icon stop
    return
end if

set foundPath to do shell script "find " & quoted form of projDir & " -name " & quoted form of fileName & " -type f | head -1"

if foundPath is "" then
    display dialog "在项目目录中找不到文件:" & fileName buttons {"OK"} default button "OK" with icon stop
    return
end if

do shell script quoted form of swiftformatPath & " " & quoted form of foundPath & " --config " & configPath 

导入到Xcode

先确保顶部配置中:

  • 工作流程收到:「没有输入」
  • 位于:「Xcode.app」

保存好之后,一般就会可以集成到 Xcode → Services里面,如果不行可以自行复制到~/Library/Services/

快捷键设置

系统设置中的快捷键设置里面去找服务这一栏,一般藏在通用里面

设置成保存按键,可以在手动触发保存的时候顺便重新格式化

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部