无法将'NSRange'(又名'_NSRange')类型的值转换为预期的参数类型'Range <index>'(又名'Range <string.characterview.index>')

时间:2016-03-03 05:24:33

标签: swift nsrange

我的代码中有一个错误,例如“无法将类型'NSRange'(又名'_NSRange')的值转换为预期的参数类型'Range'(又名'Range')”但我不知道如何解决这个问题请任何人帮助我?

我在这里发布我的代码。

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)
            }

3 个答案:

答案 0 :(得分:13)

您应该将strNumber转换为NSString:var strNumber: NSString = txtPhoneNumber.text!

更多信息:NSRange to Range<String.Index>

答案 1 :(得分:13)

Swift 4:

首先对字符串进行类型转换,然后在此类型化字符串上使用类方法

let typeCasteToStringFirst = textField.text as NSString?
let newString = typeCasteToStringFirst?.replacingCharacters(in: range, with: string)

答案 2 :(得分:1)

substringWithRange方法适用于NSString类型

var strNumber: String = txtPhoneNumber.text!

更改以上

var strNumber: NSString = txtPhoneNumber.text as! NSString