Open4
Xcode Extension のチュートリアルを行う

動機
Xcode Extensionに興味を持ったので、やっていく

プロジェクトの作り方
Xcode Extension は macOS の拡張機能なので、まずは macOS アプリを作成します。
- Create a new Xcode project
- macOS > App で新しいアプリケーションを作成
- SwiftUI、または Storyboard を選択できる
- Next をクリックしてプロジェクトを作成
拡張機能の追加
次に、拡張機能を追加します。
- File > New > Target
- macOS > App Extension > Xcode Source Editor Extension
- 良い名前をつけます
また、プロジェクトファイルから、拡張機能を追加することもできます。

ソースコードに let message = "Hello!"
を追加する拡張機能を作成する
SourceEditorCommand
を以下のコードに修正:
SourceEditorCommand.swift
import Foundation
import XcodeKit
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
let textBuffer = invocation.buffer
let lines = textBuffer.lines
let selections = textBuffer.selections
guard let selection = selections.firstObject as? XCSourceTextRange else {
completionHandler(NSError(domain: "SampleExtension", code: 401, userInfo: ["reason": "text not selected"]))
return
}
let line = selection.end.line
let end = selection.end.column
let indentSpace = String(repeating: " ", count: end)
lines.insert("\(indentSpace)let message = \"Hello!\"", at: line)
completionHandler(nil)
}
}