Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a new operator (~=) to compare strings. #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Sample/Levenshtein/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,18 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
var closeWords: [String] = []
for word in words
{
// To use operator overloading switch the following code for the one commented out.
let distance = string.levenshtein(word, caseSensitive: false, diacriticSensitive: false)
if distance <= treshold
{
closeWords.append(word)
}
/*
if string ~= word
{
closeWords.append(word)
}
*/
}

return closeWords
Expand Down
13 changes: 11 additions & 2 deletions String+Levenshtein.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@

import Foundation

func ~= (left: String, right: String) -> Bool
{
let tolerance = 40.0 // Set this to how different (in %) the strings can be while still returning true.
let averageCharacters = Double(left.characters.count + right.characters.count) / 2.0
let threshold = Int(averageCharacters * tolerance / 100)
return left.levenshtein(right, caseSensitive: false, diacriticSensitive: false) <= threshold
}

extension String
{
/**
Expand Down Expand Up @@ -39,8 +47,9 @@ extension String
/**
Compute levenshtein distance between self and given String objects

- parameter anotherString: A String object to compute the distance with
- parameter caseSensitive: Weither or not the comparison should be case sensiste
- parameter anotherString: A String object to compute the distance with
- parameter caseSensitive: Weither or not the comparison should be case sensitive
- parameter diacriticSensitive: Whether or not the comparison should be diacritic sensitive

- returns: An Int representing levenshtein distance, the higher this number is, the more words are distant
*/
Expand Down