'looping through substrings in Swift 3.0
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.
Solution 1:[1]
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)
Solution 2:[2]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric |
| Solution 2 | vadian |
