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])
}
Another option is to use
enumerated()
e.g:or for Swift 4 just use
Swift 4:
If you want to traverse over the characters of a
String
, then instead of explicitly accessing the indices of theString
, you could simply work with theCharacterView
of theString
, which conforms toCollectionType
, allowing you access to neat subsequencing methods such asprefix(_:)
and so on.If you'd like to treat the characters within the loop as strings, simply use
String(ch)
above.With regard to your comment below: if you'd like to access a range of the
CharacterView
, you could easily implement your own extension ofCollectionType
(specified for whenGenerator.Element
isCharacter
) making use of bothprefix(_:)
andsuffix(_:)
to yield a sub-collection given e.g. a half-open (from..<to
) range