车宝 發表於 2026-3-25 11:09:00

给Xcode使用完整版本的swiftformat

<ul>
<li>给Xcode使用完整版本的swiftformat
<ul>
<li>脚本配置</li>
<li>导入到Xcode</li>
<li>快捷键设置</li>
</ul>
</li>
</ul>
<h2><span class="octicon octicon-link"></span>脚本配置</h2>
<p>现在最新的Xcode有集成到swiftformat,但是因为集成的不好实时更新、执行外部config,所以还是做个自动脚本来执行终端的swiftformat<br>
<img src="https://i.imgur.com/11M2lw1.jpeg"></p>
<pre class="line-numbers"><code class="language-applescript">-- ===== 个人配置,使用前请修改 =====
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 " &amp; 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 文件:" &amp; fileName buttons {"OK"} default button "OK" with icon stop
    return
end if

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

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

do shell script quoted form of swiftformatPath &amp; " " &amp; quoted form of foundPath &amp; " --config " &amp; configPath
</code></pre>
<h2><span class="octicon octicon-link"></span>导入到Xcode</h2>
<p>先确保顶部配置中:</p>
<ul>
<li>工作流程收到:「没有输入」</li>
<li>位于:「Xcode.app」</li>
</ul>
<p>保存好之后,一般就会可以集成到 Xcode → Services里面,如果不行可以自行复制到<code>~/Library/Services/</code><br>
<img src="https://i.imgur.com/tDqYLUo.jpeg"></p>
<h2><span class="octicon octicon-link"></span>快捷键设置</h2>
<p>系统设置中的快捷键设置里面去找服务这一栏,一般藏在通用里面</p>
<p><img src="https://i.imgur.com/asLPn71.jpeg"></p>
<blockquote>
<p>设置成保存按键,可以在手动触发保存的时候顺便重新格式化</p>
</blockquote>


</div>
<div id="MySignature" role="contentinfo">
    <p>本文来自博客园,作者:MrYu4,转载请注明原文链接:https://www.cnblogs.com/MrYU4/p/19768784/geixcode-shi-yong-wan-zheng-ban-ben-deswiftformat</p><br><br>
来源:https://www.cnblogs.com/MrYU4/p/19768784/geixcode-shi-yong-wan-zheng-ban-ben-deswiftformat
頁: [1]
查看完整版本: 给Xcode使用完整版本的swiftformat