Swift - sum range.location和range.length

时间:2017-02-02 12:52:24

标签: swift string substring

我有以下Obj-c声明:

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

它的Swift等同于什么?

2 个答案:

答案 0 :(得分:0)

您应该使用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

答案 1 :(得分:0)

如果您不想使用子字符串:

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