我目前使用带有起始索引和长度的 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/