所以我发现了与转换 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/