はじめに
文章の差分検索ツールを作ろうかなって思い、
ちょっと調べたところ、difference
という機能があることを知ったので記事にしておきます。
実装
import Foundation
let text1 = "2つの文章の差分を検索します"
let text2 = "2つのブンショウの差分を検索します。"
print(text1.difference(from: text2))
// CollectionDifference<Character>(insertions: [Swift.CollectionDifference<Swift.Character>.Change.insert(offset: 0, element: "2", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.insert(offset: 3, element: "文", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.insert(offset: 4, element: "章", associatedWith: nil)], removals: [Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 0, element: "2", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 3, element: "ブ", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 4, element: "ン", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 5, element: "シ", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 6, element: "ョ", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 7, element: "ウ", associatedWith: nil), Swift.CollectionDifference<Swift.Character>.Change.remove(offset: 17, element: "。", associatedWith: nil)])
おわり
出力結果はinsert
とremove
でちゃんと分かれています。
これを関数でコネコネしてAttributedStringに変換して、
insert
には緑の背景色、remove
には赤の背景色を付与すれば、Gitのようなdiffがすぐ出来そうですね
割と簡単そうなので差分確認アプリ作ろうか迷います。