The following was possible with Swift 2.2:
let m = "alpha"
for i in m.startIndex..<m.endIndex {
print(m[i])
}
a
l
p
h
a
With 3.0, we get the following error:
Type 'Range' (aka 'Range') does not conform to protocol 'Sequence'
I am trying to do a very simple operation with strings in swift -- simply traverse through the first half of the string (or a more generic problem: traverse through a range of a string).
I can do the following:
let s = "string"
var midIndex = s.index(s.startIndex, offsetBy: s.characters.count/2)
let r = Range(s.startIndex..<midIndex)
print(s[r])
But here I'm not really traversing the string. So the question is: how do I traverse through a range of a given string. Like:
for i in Range(s.startIndex..<s.midIndex) {
print(s[i])
}
The best way to do this is :-
for more details visit here
You can traverse a string by using
indices
property of thecharacters
property like this:From the documentation in section Strings and Characters - Counting Characters:
emphasis is my own.
This will not work:
Swift 4.2
Simply:
Iterating over characters in a string is cleaner in Swift 4:
Use the following:
Taken from Migrating to Swift 2.3 or Swift 3 from Swift 2.2
To concretely demonstrate how to traverse through a range in a string in Swift 4, we can use the
where
filter in afor
loop to filter its execution to the specified range:iterateStringByRange("string", from: 1, to: 3)
will printt
,r
andi