string - 将 String.Index 转换为 Int 或将 Range<String.Index> 转换为 NSRange

标签 string swift

所以我发现了与转换 NSRange 的情况相关的问题至 Range<String.Index> ,但实际上我遇到了相反的问题。

很简单,我有一个 String和一个 Range<String.Index>并需要将后者转换为 NSRange用于旧函数。

到目前为止,我唯一的解决方法是像这样获取一个子字符串:

func foo(theString: String, inRange: Range<String.Index>?) -> Bool {
    let theSubString = (nil == inRange) ? theString : theString.substringWithRange(inRange!)
    return olderFunction(theSubString, NSMakeRange(0, countElements(theSubString)))
}

这当然有效,但它不是很漂亮,我宁愿避免必须获取子字符串并以某种方式使用范围本身,这可能吗?

最佳答案

如果您查看 String.Index 的定义,您会发现:

struct Index : BidirectionalIndexType, Comparable, Reflectable {

    /// Returns the next consecutive value after `self`.
    ///
    /// Requires: the next value is representable.
    func successor() -> String.Index

    /// Returns the previous consecutive value before `self`.
    ///
    /// Requires: the previous value is representable.
    func predecessor() -> String.Index

    /// Returns a mirror that reflects `self`.
    func getMirror() -> MirrorType
}

所以实际上没有办法将它转换为 Int 并且这是有充分理由的。根据字符串的编码,单个字符占用不同的字节数。唯一的方法是计算需要多少 successor 操作才能达到所需的 String.Index

编辑 String 的定义在不同的 Swift 版本中发生了变化,但答案基本相同。要查看当前定义,只需 CMD 键单击 XCode 中的 String 定义即可到达根目录(也适用于其他类型)。

distanceTo 是对各种协议(protocol)的扩展。单击 CMD 后,只需在 String 源中查找它即可。

关于string - 将 String.Index 转换为 Int 或将 Range<String.Index> 转换为 NSRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128554/

相关文章:

javascript - 使用 RegExp、String 或其他方法确定类中声明的属性的值类型

java - 如何使 TextView 中的一个单词与字符串中的长文本可单击?

ios - 容器 View - 没有导出可能

ios - iOS 10 上的 UIView mask

ios - 在滚动到顶部的 UITextView 上检测向下滑动

python - 我的 def 函数出了什么问题?如何修复它?

以逗号分隔的 Javascript 字符串

sql - 微软 Access : How to sort text column by length of its text string?

ios - 如何在 UIImageView 中以编程方式使 UIButton 居中?

swift - 如何使用 SF Symbol 作为图像从 UIImageView 转换两个阴影?