博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift中NSRange和Range的转换
阅读量:4078 次
发布时间:2019-05-25

本文共 1355 字,大约阅读时间需要 4 分钟。

最近项目再使用swift重构,遇到Range和NSRange转换的问题,这里记录下:

因为要使用NSRange,所以有了下面这段代码,将String转换为NSString后调用 range(of searchString: String) -> NSRange

这种处理方法其实就是使用到了OC的方法了

let textStr = "登陆及代表同意《用户协议》与《隐私政策》"//获取NSRangelet range = NSString(string: textStr).range(of: "《隐私政策》")

 以下为其他转换方法:

extension String {         //Range转换为NSRange    func toNSRange(_ range: Range
) -> NSRange { guard let from = range.lowerBound.samePosition(in: utf16), let to = range.upperBound.samePosition(in: utf16) else { return NSMakeRange(0, 0) } return NSMakeRange(utf16.distance(from: utf16.startIndex, to: from), utf16.distance(from: from, to: to)) } //NSRange转换为Range func toRange(_ range: NSRange) -> Range
? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil } guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil } guard let from = String.Index(from16, within: self) else { return nil } guard let to = String.Index(to16, within: self) else { return nil } return from ..< to } }

使用如下:

let textStr = "登陆及代表同意《用户协议》与《隐私政策》"//Range->NSRangelet nsrange = textStr.toNSRange(linkStr.range(of: "《隐私政策》")//NSRange->Rangelet range = textStr.toRange(nsrange)

 

转载地址:http://idsni.baihongyu.com/

你可能感兴趣的文章
C# 托管与非托管
查看>>
Node.js中的事件驱动编程详解
查看>>
mongodb管理与安全认证
查看>>
nodejs内存控制
查看>>
MongoDB 数据文件备份与恢复
查看>>
MongoDB数据库插入、更新和删除操作详解
查看>>
MongoDB文档(Document)全局唯一ID的设计思路
查看>>
mongoDB简介
查看>>
Redis持久化存储(AOF与RDB两种模式)
查看>>
memcached工作原理与优化建议
查看>>
Redis与Memcached的区别
查看>>
程序员最核心的竞争力是什么?
查看>>
linux CPU个数查看
查看>>
消息队列设计精要
查看>>
分布式存储系统设计(1)—— 系统架构
查看>>
MySQL数据库的高可用方案总结
查看>>
常用排序算法总结(一) 比较算法总结
查看>>
SSH原理与运用
查看>>
SIGN UP BEC2
查看>>
出现( linker command failed with exit code 1)错误总结
查看>>