4

I want to replace some character occurrences with english letters using Swift. Replace code:

let turkish = ["ı", "ğ", "ü", "ş", "ö", "ç"]
let english = ["i", "g", "u", "s", "o", "c"]

var city = "Ağri"
var result = ""

for i in 0..<turkish.count {
    var target = turkish[i]
    var destination = english[i]

    result = city.stringByReplacingOccurrencesOfString(target, withString: destination, options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)
}

It does not replace "ğ" with "g". What's strange is that, if I type it directly like this:

result = city.stringByReplacingOccurrencesOfString("ğ", withString: "g", options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)

it works perfectly fine.

Why doesn't it, when I first assign the value to a String variable?

Cœur
  • 37,241
  • 25
  • 195
  • 267
aymeba
  • 934
  • 1
  • 11
  • 26

2 Answers2

12

It looks like you are trying to remove a variety of accents and diacritics. One way that you can do that is using CFStringTransform.

In Swift it would look something like this:

let original = "šÜįéïöç"
var mutableString = NSMutableString(string: original) as CFMutableStringRef
CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0))

let normalized = (mutableString as NSMutableString).copy() as! NSString
// = sUieioc

Edit

As was pointed out by Martin R in the comments. You can do the same without Core Foundation:

let original = "šÜįéïöç"
let normalized = original.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
// = sUieioc
Community
  • 1
  • 1
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
  • 4
    The same can be done directly on a Swift string, without CoreFoundation: http://stackoverflow.com/questions/29521951/how-to-remove-diacritics-from-a-string-in-swift (which I learned from http://stackoverflow.com/a/15155624/1187415). – Martin R Apr 19 '15 at 14:53
  • @MartinR Interesting. I didn't know that. – David Rönnqvist Apr 19 '15 at 14:57
  • thanks. It is a better solution than iterating and replacing the characters. – aymeba Apr 19 '15 at 14:57
  • 1
    *Remark:* This will not replace "ı" (LATIN SMALL LETTER DOTLESS I) by "i". – Martin R Apr 03 '19 at 18:43
2

It occurs because you replace the occurrences of city but assigning the new value to result. This way only the last character is replaced in result. Just remove the result variable and change this line:

result = city.stringByReplacingOccurrencesOfString(target, withString: destination, options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)

to this:

city = city.stringByReplacingOccurrencesOfString(target, withString: destination, options: NSStringCompareOptions.CaseInsensitiveSearch | NSStringCompareOptions.LiteralSearch, range: nil)
dehlen
  • 7,325
  • 4
  • 43
  • 71