We can use distance(from:to:) method to get the start index and end index in Swift.
distance(from:to:) -> Returns the distance between two indices.
Declaration
func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance
Example:
import Foundation
let sentence = "This article is written by Yogesh Chauhan"
if let range = sentence.range(of: "Yogesh") {
let startIndex = sentence.distance(from: sentence.startIndex, to: range.lowerBound)
let endIndex = sentence.distance(from: sentence.startIndex, to: range.upperBound)
print(startIndex)
print(endIndex)
}
//output
27
33
end indexof start substring