【问题标题】:Swift - sum range.location and range.length [duplicate]Swift - 总和 range.location 和 range.length [重复]
【发布时间】:2017-06-19 13:22:40
【问题描述】:

我有以下 Obj-c 语句:

string = [string substringFromIndex:(range.location + range.length)];

它的 Swift 等价物是什么?

【问题讨论】:

  • 你就不能查一下吗?这似乎根本不是一个艰难的转换......
  • 查看此链接了解详情 - click here
  • @BenjaminLowry,在 Swift 中有多种范围类型,没有 Xcode 帮助,这是一个艰难的转换!

标签: swift string substring


【解决方案1】:

你应该使用substring(from:):

var string = "Hello World"

string = string.substring(from: string.index(string.startIndex, offsetBy: 6))

print(string) // "World"

另外,您可能想使用substring(to:)

let hello = string.substring(to: string.index(string.startIndex, offsetBy: 5))

print(hello) // "Hello"

有关String.Index的更多信息,请查看question/answer

【讨论】:

  • 所以答案是“用6替换range.length”?
【解决方案2】:

如果不想使用子字符串:

let string = "abcdefghijklm"
let startPoint = 2
let length = 5

let startIndex = string.index(string.startIndex, offsetBy: startPoint)
let endIndex = string.index(startIndex, offsetBy: length)

let result = string[startIndex ..< endIndex]
print(result)         // cdefg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-07
    • 2021-04-15
    • 1970-01-01
    • 2022-01-02
    • 2018-12-15
    • 1970-01-01
    • 2018-07-25
    • 2019-11-28
    相关资源
    最近更新 更多