Skip to content

Commit 593188f

Browse files
committed
Add examples to UTF8SpanIterators
1 parent 8e96210 commit 593188f

File tree

1 file changed

+42
-7
lines changed

1 file changed

+42
-7
lines changed

stdlib/public/core/UTF8SpanIterators.swift

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,19 @@ extension UTF8Span {
2121
.init(self)
2222
}
2323

24-
// **TODO**: Examples in below doc
25-
26-
/// Iterate the `Unicode.Scalar`s contents of a `UTF8Span`.
24+
/// Iterate the `Unicode.Scalar`s contents of a `UTF8Span`.
25+
///
26+
/// func printScalarValues(_ string: borrowing String) {
27+
/// var iterator = string.utf8Span.makeUnicodeScalarIterator()
28+
/// while let scalar = iterator.next() {
29+
/// print(scalar.escaped(asASCII: true))
30+
/// }
31+
/// }
32+
///
33+
/// let string = "A🎉"
34+
/// printScalarValues(string)
35+
/// // Prints "A"
36+
/// // Prints "\u{0001F389}"
2737
@frozen
2838
public struct UnicodeScalarIterator: ~Escapable {
2939
public let codeUnits: UTF8Span
@@ -156,10 +166,18 @@ extension UTF8Span {
156166
return numSkipped
157167
}
158168

159-
// TODO: Example for reset docs
160-
161169
/// Reset to the nearest scalar-aligned code unit offset `<= i`.
162170
///
171+
/// func printScalarAfterReset(_ string: borrowing String) {
172+
/// var iterator = string.utf8Span.makeUnicodeScalarIterator()
173+
/// iterator.reset(roundingBackwardsFrom: 8) // Position 8 is mid-emoji, rounds back to 6
174+
/// if let scalar = iterator.next() {
175+
/// print(scalar) // Prints "🌍" (emoji starts at byte 6)
176+
/// }
177+
/// }
178+
/// let string = "Hello 🌍"
179+
/// printScalarAfterReset(string)
180+
///
163181
/// - Complexity: O(1)
164182
@lifetime(self: copy self)
165183
public mutating func reset(roundingBackwardsFrom i: Int) {
@@ -240,9 +258,26 @@ extension UTF8Span {
240258
.init(self)
241259
}
242260

243-
// **TODO**: Examples in below doc
244-
245261
/// Iterate the `Character` contents of a `UTF8Span`.
262+
///
263+
/// func countCharacters(_ string: borrowing String) {
264+
/// var iterator = string.utf8Span.makeCharacterIterator()
265+
/// var count = 0
266+
/// while let character = iterator.next() {
267+
/// count += 1
268+
/// print("Character \(count): \(character)")
269+
/// }
270+
/// print("Total: \(count) characters")
271+
/// }
272+
///
273+
/// let string = "لاهور"
274+
/// countCharacters(string)
275+
/// // Prints "Character 1: ل"
276+
/// // Prints "Character 2: ا"
277+
/// // Prints "Character 3: ه"
278+
/// // Prints "Character 4: و"
279+
/// // Prints "Character 5: ر"
280+
/// // Prints "Total: 5 characters"
246281
public struct CharacterIterator: ~Escapable {
247282
public let codeUnits: UTF8Span
248283

0 commit comments

Comments
 (0)