Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>') to expected argument type 'NSRange' (aka '_NSRange')

I am trying to replace a substring with attributed String. Following is my code.

let searchText = self.searchBar.text!
let name = item.firstName ?? ""
let idNo = "Employee Id. \(item.employeeId ?? "NA")"

if let range = name.range(of: searchText, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)
{
    let attributedSubString = NSAttributedString.init(string: name.substring(with: range), attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 17)])
    let normalNameString = NSMutableAttributedString.init(string: name)
    normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString)
    cell.name.attributedText = normalNameString
}
else
{
    cell.name.text = name
}

I am getting compile time error:

"Cannot convert value of type 'Range' (aka 'Range') to expected argument type 'NSRange' (aka '_NSRange')".

What should I change here?

like image 932
Bharath Reddy Avatar asked Sep 15 '17 05:09

Bharath Reddy


1 Answers

You can use NSString and NSRange, also you need to change this line normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString) and use this one instead normalNameString.replaceCharacters(in: nsRange, with: attributedSubString) because mutableString is NSMutableString, and replacingCharacters expect String and not NSAttributtedString

Full code (Updated for Swift5)

    let nsRange = NSString(string: name).range(of: searchText, options: String.CompareOptions.caseInsensitive)

    if nsRange.location != NSNotFound
    {
        let attributedSubString = NSAttributedString.init(string: NSString(string: name).substring(with: nsRange), attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)])
        let normalNameString = NSMutableAttributedString.init(string: name)
        normalNameString.replaceCharacters(in: nsRange, with: attributedSubString)
        cell.name.attributedText = normalNameString
    }
    else
    {
        cell.name.text = name
    }
like image 174
Reinier Melian Avatar answered Oct 24 '22 09:10

Reinier Melian