Swift 3.0 の String.range() を使う
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")
}
一致の場所は7から12までで、「World」は元々の文字列の中でこの範囲に存在します。