simonbs/textdiffing
- Compare two strings and generate [AttributedString](https://developer.apple.com/documentation/foundation/attributedstring) / [NSAttributedString](https://developer.apple.com/documentation/foundation/nsattributedstring) highlighting differences
✨ Features
- Compare two strings and generate AttributedString / NSAttributedString highlighting differences
- Customize appearance of changes
- Supports word- and character-level diffing
- Lightweight and easy to integrate
📦 Adding the Package
TextDiffing is distributed using Swift Package Manager. Install TextDiffing in a project by adding it as a dependency in your Package.swift manifest or through “Package Dependencies” in project settings.
let package = Package(
dependencies: [
.package(url: "git@github.com:simonbs/textdiffing.git", from: "1.0.2")
]
)📖 Documentation
The documentation is <a href="https://swiftpackageindex.com/simonbs/textdiffing/documentation">available on Swift Package Index</a>.
🚀 Getting Started
Use the TextDiffer to compare two strings.
let result = TextDiffer.diff(text, and: otherText)The returned TextDiffResult has two properties:
|Property|Description| |-|-| |attributedString|The formatted AttributedString representing the differences.| |changeCount|The number of changes (insertions or removals) between the texts.|
let attributedString = result.attributedString
let changeCount = result.changeCountThe TextDiffer.diff(_:and:) method also takes the following options.
|Option|Description| |-|-| |strikethroughRemovedText|Adds a strikethrough to removed text.| |tokenizeByCharacter|Tokenizes the input by individual characters.| |tokenizeByWord|Tokenizes the input by words (default).|
By default, text is tokenized by word. You can combine multiple options to customize behavior.
let result = TextDiffer.diff(text, and: otherText, options: [.tokenizeByCharacter, .strikethroughRemovedText])You can customize the appearance of inserted and removed text by providing your own TextDiffStyle. This lets you control the background color used for visual highlighting.
let style = TextDiffStyle(
insertedBackground: UIColor.systemGreen.withAlphaComponent(0.3),
removedBackground: UIColor.systemRed.withAlphaComponent(0.3)
)
let result = TextDiffer.diff(text, and: otherText, style: style)You may also use the extensions on NSAttributedString and AttributedString.
let attributedString = AttributedString(diffing: text, and: otherText)
let attributedString = NSAttributedString(diffing: text, and: otherText)The initializers provided by the extensions also optionally take a style and options.
let attributedString = AttributedString(diffing: text, and: otherText, style: style, options: options)
let attributedString = NSAttributedString(diffing: text, and: otherText, style: style, options: options)Package Metadata
Repository: simonbs/textdiffing
Default branch: main
README: README.md