Как удалить диакритические знаки (или акценты) из String
(например, изменить "één" to "een" ) в Swift? Должен ли я вернуться к NSString
или это можно сделать в Swift?
Как удалить диакритические символы из строки в Swift?
Ответ 1
Вы можете работать непосредственно с Swift String
(если импортируется "Foundation" ):
let foo = "één"
let bar = foo.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
print(bar) // een
Swift 3:
let foo = "één"
let bar = foo.folding(options: .diacriticInsensitive, locale: .current)
print(bar) // een
Ответ 2
Обновить до ответа @MartinR... расширение Swift 3, чтобы предоставить строку для сортировки/поиска, которая может быть полезной для кого-то...
extension String {
var forSorting: String {
let simple = folding(options: [.diacriticInsensitive, .widthInsensitive, .caseInsensitive], locale: nil)
let nonAlphaNumeric = CharacterSet.alphanumerics.inverted
return simple.components(separatedBy: nonAlphaNumeric).joined(separator: "")
}
}
например.
print("Mÿ nâMe ís jÄço´B".forSorting) // "mynameisjacob"
Ответ 3
Обновление ответа для Swift 5.0.1
func toNoSmartQuotes() -> String {
let userInput: String = self
return userInput.folding(options: .diacriticInsensitive, locale: .current)
}
и используй его someTextField.text.toNoSmartQuotes()