我有以下Obj-c声明:
string = [string substringFromIndex:(range.location + range.length)];
它的Swift等同于什么?
答案 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