4
3

【Swift】2つの要素の差分を取得する

Posted at

はじめに

文章の差分検索ツールを作ろうかなって思い、
ちょっと調べたところ、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)])

おわり

出力結果はinsertremoveでちゃんと分かれています。
これを関数でコネコネしてAttributedStringに変換して、
insertには緑の背景色、removeには赤の背景色を付与すれば、Gitのようなdiffがすぐ出来そうですね

割と簡単そうなので差分確認アプリ作ろうか迷います。

4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3