最近在使用NSRange获取字符串的部分字符串时,遇到一个编译报错:
Cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')
我的代码是这样的:
let str = "swift"
var range = NSRange()
range.location = 0
range.length = 2
var rString = str.substring(with: range)
这里只需要将String类型转换为NSString类型即可,即将代码修改如下:
let str = "swift"
var range = NSRange()
range.location = 0
range.length = 2
let ocStr = str as NSString
let rString = ocStr.substring(with: range)
print(rString)