Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

erdinc27

macrumors regular
Original poster
Jul 20, 2011
168
1
I have two strings. I want to compare them and if they matches %70 then i will trigger a method. But I couldn't find a way to compare them. How can I achieve that?
 
If you are only looking for a 70% match I think you're going to have to check one letter at a time and keep track of how many match, then perform division to meet the 70% requirement. NSString does have a compare function, but that will only return true if its a 100% match.
 
Here is some code I wrote that will let you compare two Strings in Swift 3. It has a 'caseSensitive' parameter if you don't care about case sensitivity.

Code:
extension String {
    func compare(to string : String, caseSensitive : Bool) -> Double // returns 0-1 match (ie. 70% match would return 0.7)
    {
        let string = caseSensitive ? string : string.lowercased();
      
        var matches = 0.0;
      
        for (i, char) in (caseSensitive ? self : self.lowercased()).enumerated() {
            guard i < string.count else {break};
            matches += (char == string[string.characters.index(string.startIndex, offsetBy: i)]) ? 1 : 0;
        }
      
        return matches / Double(self.count > string.count ? self.count : string.count);
    }
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.