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

3

15

I Have a error in my code like "Cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range' (aka 'Range')" but I don't know how to solve this please any one help me?

Here I post my code.

NSUserDefaults.standardUserDefaults().setObject("Hey I have started using this Chat App", forKey: "Status")
            var strNumber: String = txtPhoneNumber.text!
            var myRange: NSRange = NSMakeRange(0, 2)
            var myRange1: NSRange = NSMakeRange(0, 1)
            var ran: String = strNumber.substringWithRange(myRange)  ------>  //This line error shows.
            var ran1: String = strNumber.substringWithRange(myRange1)
            if (ran == "00") || (ran == "60") || (ran == "62") || (ran == "65") || (ran == "91") || (ran == "44") {
                strNumber = strNumber.stringByReplacingOccurrencesOfString(ran, withString: "") as String
            }
            else if (ran1 == "0") {

                strNumber = strNumber.stringByReplacingOccurrencesOfString(ran1, withString: myRange1) as NSString
                //str_number = str_number.stringByReplacingOccurrencesOfString(ran1, withString: "", options: NSCaseInsensitiveSearch, range: myRange1)
            }
Glassman answered 3/3, 2016 at 5:24 Comment(0)
K
17

You should convert strNumber to NSString: var strNumber: NSString = txtPhoneNumber.text!

More here: NSRange to Range<String.Index>

Kristiekristien answered 3/3, 2016 at 11:42 Comment(1)
Thank you very much for your help, it is useful for me...@courteousGlassman
H
15

Swift 4:

First typecaste to a string, and then use the class method on this typecasted string

let typeCasteToStringFirst = textField.text as NSString?
let newString = typeCasteToStringFirst?.replacingCharacters(in: range, with: string)
Hawks answered 20/10, 2017 at 5:30 Comment(0)
G
1

substringWithRange method works for NSString type

var strNumber: String = txtPhoneNumber.text!

change above line

var strNumber: NSString = txtPhoneNumber.text as! NSString
Gorge answered 7/9, 2016 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.