swift string.nsrange.swift
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift string.nsrange.swift相关的知识,希望对你有一定的参考价值。
// こういう相互変換が正しそう
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))
}
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
}
}
// 利用例
let str = "a
以上是关于swift string.nsrange.swift的主要内容,如果未能解决你的问题,请参考以下文章
Swift入门系列--Swift官方文档(2.2)--中文翻译--About Swift 关于Swift
swift 示例BS swift.swift
swift swift_bug.swift
ios 整理(一)swift和oc的区别
swift swift_extension5.swift
swift swift_optional4.swift