ios - 如何在 Swift 中使用带有 startIndex 和长度的 substringWithRange()

标签 ios swift

我目前使用带有起始索引和长度的 substringWithRange():

let str = "Hello World"

let index = 0
let length = 3

str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(index), end: str.startIndex.advancedBy(index + length))) // "Hel"

这很好用,但是有什么方法可以使用更简单、更优雅的语法吗?

我可以使用 NSRange,但我只想使用纯 Swift 代码。

最佳答案

extension String
{
    public func substringWithRange(range: Range<Index.Distance>) -> String
    {
        return substringWithRange(startIndex.advancedBy(range.startIndex)..<startIndex.advancedBy(range.endIndex))
    }
}

str.substringWithRange(index..<index + length)

关于ios - 如何在 Swift 中使用带有 startIndex 和长度的 substringWithRange(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437394/

相关文章:

iOS - 通过 Swift 更改约束的乘数

ios - 根据按下的按钮,通过 Segue 传递变量返回的对象

与多个 Web 服务快速通信

ios - 在 iOS 应用程序安装上创建子文件夹

ios - iMessage 应用程序 - 将 GIF 显示为 UICollectionViewCell 时内存泄漏?

ios - 在 iOS 上通过 Swift 执行 SSH

ios - 迪尔德 : Symbol not found HeapBufferStorage

ios - 在 performSelectorInBackground 中将参数传递给 @selector?

iphone - 如何确定iOS促销代码是否已兑换?

ios - 从自定义单元格获取数据到 TableViewController