在Swift 3.0中,你可以使用String.range来获取子字符串在原始字符串中的位置。这里是一个简单的示例:
let str = "Hello, World!"
let range = str.range(of: "World")
if let range = range {
let startIndex = str.distance(from: str.startIndex, to: range.lowerBound)
let endIndex = str.distance(from: str.startIndex, to: range.upperBound)
print("Found at index \(startIndex) to \(endIndex)")
} else {
print("Not found")
}
输出结果将是 “Found at index 7 to 12”,表示子字符串 “World” 在原始字符串中的位置范围。