Transform an array into any other array of the same type, or a string into any other string, using only the three transformations replace
, delete
and insert
.
- Open your Swift package in GNOME Builder, Xcode, or any other IDE.
- Open the
Package.swift
file. - Into the
Package
initializer, underdependencies
, paste:
.package(url: "https://github.com/david-swift/LevenshteinTransformations", from: "0.1.0")
let source = [1, 2, 5, 6]
let target = [0, 1, 5, 6, 10]
There are three functions available for arrays containing elements conforming to Equatable
and strings.
Get the Levenshtein distance with levenshteinDistance(to:)
:
print(source.levenshteinDistance(to: target))
This example outputs 3
.
Get the individual transformation steps with getTransformations(to:)
.
print(source.getTransformations(to: target).map { $0.description(source: source) }.joined(separator: "\n"))
This example prints the descriptions of the transformations:
Replace '1' at position 0 with '0'
Replace '2' at position 1 with '1'
Insert '10' at position 4
Directly run functions for the replace
, delete
and insert
transformations using the transform(to:functions:)
function.
var modified = source
source.transform(
to: target,
functions: .init { index, element in
modified[index] = element
} delete: { index in
modified.remove(at: index)
} insert: { index, element in
modified.insert(element, at: index)
}
)
print(modified == target)
This example outputs true
.
The same functions are available for arrays with identifiable elements, but they are named differently to avoid conflicts:
identifiableLevenshteinDistance(to:)
identifiableGetTransformations(to:)
identifiableTransform(to:functions:)
- The contributors
- SwiftLint for checking whether code style conventions are violated
- The programming language Swift
- SourceDocs used for generating the docs