Reputation: 893
What is the best way to loop through a substring in Swift 3.0?
var start = s.startIndex
var end = s.index(s.endIndex, offsetBy: -10)
for i in start...end {
}
The following code throws an error: Type ClosedRange<String.Index> (aka ‘ClosedRange<String.CharacterView.Index>’) does not conform to Sequence protocol
.
Upvotes: 1
Views: 471
Reputation: 285072
String.Index
cannot be used in a for loop, but (sub)strings can be enumerated
var start = s.startIndex
var end = s.index(s.endIndex, offsetBy: -10)
for (index, character) in s[start...end].enumerated() {
print(index, character)
}
Upvotes: 0
Reputation: 6459
start
and end
are types of String.Index
, and they cannot be used in a for loop; instead, you can get substring
within the following range:
var start = s.startIndex
var end = s.index(s.endIndex, offsetBy: -10)
let range = Range(uncheckedBounds: (lower: start, upper: end))
let subString = s.substring(with: range)
Upvotes: 2