
Swift
使用 Swift 编程语言时,经常会遇到需要将 NSRange 转换为 Range
Swiftimport Foundationextension 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</p> }}// 使用示例:let str = "Hello, World!"let nsRange = NSRange(location: 7, length: 5)if let range = str.range(from: nsRange) { let substring = str[range] print(substring) // 输出 "World"}在上述示例代码中,我们扩展了 String 类型,添加了一个 range(from:) 方法,用于将 NSRange 转换为 RangeSwiftimport Foundationlet str = "Hello, World!"let nsRange = NSRange(location: 7, length: 5)if let range = str.range(from: nsRange) { let substring = str[range] print(substring) // 输出 "World"}在这个案例代码中,我们首先定义了一个字符串 str,并创建了一个 NSRange 对象 nsRange,该对象表示从位置 7 开始,长度为 5 的子字符串。然后,我们调用 String 类型的 range(from:) 方法,将 nsRange 转换为 RangeCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号