Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 642 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Swift 3.0 iterate over String.Index range

#11
If you want to traverse over the characters of a `String`, then instead of explicitly accessing the indices of the `String`, you could simply work with the [`CharacterView`](

[To see links please register here]

) of the `String`, which conforms to [`CollectionType`](

[To see links please register here]

), allowing you access to neat subsequencing methods such as `prefix(_:)` and so on.

/* traverse the characters of your string instance,
up to middle character of the string, where "middle"
will be rounded down for strings of an odd amount of
characters (e.g. 5 characters -> travers through 2) */
let m = "alpha"
for ch in m.characters.prefix(m.characters.count/2) {
print(ch, ch.dynamicType)
} /* a Character
l Character */

/* round odd division up instead */
for ch in m.characters.prefix((m.characters.count+1)/2) {
print(ch, ch.dynamicType)
} /* a Character
l Character
p Character */

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 of `CollectionType` (specified for when `Generator.Element` is `Character`) making use of both `prefix(_:)` and `suffix(_:)` to yield a sub-collection given e.g. a half-open (`from..<to`) range

/* for values to >= count, prefixed CharacterView will be suffixed until its end */
extension CollectionType where Generator.Element == Character {
func inHalfOpenRange(from: Int, to: Int) -> Self {
guard case let to = min(to, underestimateCount()) where from <= to else {
return self.prefix(0) as! Self
}
return self.prefix(to).suffix(to-from) as! Self
}
}

/* example */
let m = "0123456789"
for ch in m.characters.inHalfOpenRange(4, to: 8) {
print(ch) /* \ */
} /* 4 a (sub-collection) CharacterView
5
6
7 */
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through