Open4

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

とんとんぼとんとんぼ

プロジェクトの作り方

Xcode Extension は macOS の拡張機能なので、まずは macOS アプリを作成します。

  1. Create a new Xcode project
  2. macOS > App で新しいアプリケーションを作成
  3. SwiftUI、または Storyboard を選択できる
  4. Next をクリックしてプロジェクトを作成

拡張機能の追加

次に、拡張機能を追加します。

  1. File > New > Target
  2. macOS > App Extension > Xcode Source Editor Extension
  3. 良い名前をつけます
    また、プロジェクトファイルから、拡張機能を追加することもできます。

とんとんぼとんとんぼ

ソースコードに 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)
   }
}