Structure

String.CharacterView

A view of a string’s contents as a collection of characters.

Overview

In Swift, every string provides a view of its contents as characters. In this view, many individual characters—for example, “é”, “김”, and “🇮🇳”—can be made up of multiple Unicode code points. These code points are combined by Unicode’s boundary algorithms into extended grapheme clusters, represented by the Character type. Each element of a CharacterView collection is a Character instance.

let flowers = "Flowers 💐"
for c in flowers.characters {
    print(c)
}
// F
// l
// o
// w
// e
// r
// s
//
// 💐

You can convert a String.CharacterView instance back into a string using the String type’s init(_:) initializer.

let name = "Marie Curie"
if let firstSpace = name.characters.index(of: " ") {
    let firstName = String(name.characters.prefix(upTo: firstSpace))
    print(firstName)
}
// Prints "Marie"

Nested Types

String.CharacterView.Index

A position in a string’s CharacterView instance.

Symbols

Type Aliases

Initializers

init()

Creates an empty character view.

init<S>(S)

Creates a new character view containing the characters in the given sequence.

init(String)

Creates a view of the given string.

Instance Properties

var endIndex: String.CharacterView.Index

A character view’s “past the end” position—that is, the position one greater than the last valid subscript argument.

var startIndex: String.CharacterView.Index

The position of the first character in a nonempty character view.

Instance Methods

func append(Character)

Appends the given character to the character view.

func append<S>(contentsOf: S)

Appends the characters in the given sequence to the character view.

func index(after: String.CharacterView.Index)

Returns the next consecutive position after i.

func index(before: String.CharacterView.Index)

Returns the previous consecutive position before i.

func replaceSubrange<C>(Range<String.CharacterView.Index>, with: C)

Replaces the characters within the specified bounds with the given characters.

func reserveCapacity(Int)

Reserves enough space in the character view’s underlying storage to store the specified number of ASCII characters.

Subscripts

subscript(String.CharacterView.Index)

Accesses the character at the given position.

subscript(Range<String.CharacterView.Index>)

Accesses the characters in the given range.