Range是无法通过 as? 强制转换到NSRange的。
强制转换会crash Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1000b4488)
var mutableAttrStr = NSMutableAttributedString.init()
// range 不能用as? 强制转换
let substringRange = mutableAttrStr.string.range(of: friendModel.userName!)
friendModel.range = mutableAttrStr.string.nsRange(from: substringRange!)
//range转换为NSRange
//扩展的是String类,不可改为NSRange或者Range的扩展,因为samePosition,utf16是String里的
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
}
//NSRange转化为range
//扩展的是String类,不可改为NSRange或者Range的扩展,因为utf16是String里的
extension String {
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
}
|