在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” 在原始字符串中的位置范圍。