Structure

Substring

A slice of a string.

Declaration

@frozen struct Substring

Overview

When you create a slice of a string, a Substring instance is the result. Operating on substrings is fast and efficient because a substring shares its storage with the original string. The Substring type presents the same interface as String, so you can avoid or defer any copying of the string’s contents.

The following example creates a greeting string, and then finds the substring of the first sentence:

let greeting = "Hi there! It's nice to meet you! 👋"
let endOfSentence = greeting.firstIndex(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"

You can perform many string operations on a substring. Here, we find the length of the first sentence and create an uppercase version.

print("'\(firstSentence)' is \(firstSentence.count) characters long.")
// Prints "'Hi there!' is 9 characters long."

let shoutingSentence = firstSentence.uppercased()
// shoutingSentence == "HI THERE!"

Converting a Substring to a String

This example defines a rawData string with some unstructured data, and then uses the string’s prefix(while:) method to create a substring of the numeric prefix:

let rawInput = "126 a.b 22219 zzzzzz"
let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
// numericPrefix is the substring "126"

When you need to store a substring or pass it to a function that requires a String instance, you can convert it to a String by using the String(_:) initializer. Calling this initializer copies the contents of the substring to a new string.

func parseAndAddOne(_ s: String) -> Int {
    return Int(s, radix: 10)! + 1
}
_ = parseAndAddOne(numericPrefix)
// error: cannot convert value...
let incrementedPrefix = parseAndAddOne(String(numericPrefix))
// incrementedPrefix == 127

Alternatively, you can convert the function that takes a String to one that is generic over the StringProtocol protocol. The following code declares a generic version of the parseAndAddOne(_:) function:

func genericParseAndAddOne<S: StringProtocol>(_ s: S) -> Int {
    return Int(s, radix: 10)! + 1
}
let genericallyIncremented = genericParseAndAddOne(numericPrefix)
// genericallyIncremented == 127

You can call this generic function with an instance of either String or Substring.

Topics

Type Aliases

typealias Substring.Element

A type representing the sequence’s elements.

typealias Substring.ExtendedGraphemeClusterLiteralType

A type that represents an extended grapheme cluster literal.

typealias Substring.Index

A type that represents a position in the collection.

typealias Substring.Indices

A type that represents the indices that are valid for subscripting the collection, in ascending order.

typealias Substring.Iterator

A type that provides the collection’s iteration interface and encapsulates its iteration state.

typealias Substring.StringInterpolation

The type each segment of a string literal containing interpolations should be appended to.

typealias Substring.StringLiteralType

A type that represents a string literal.

typealias Substring.SubSequence

A sequence that represents a contiguous subrange of the collection’s elements.

typealias Substring.UnicodeScalarLiteralType

A type that represents a Unicode scalar literal.

Initializers

init()

Creates an empty substring.

init(String)

Instantiates an instance of the conforming type from a string representation.

init<S>(S)

Creates a new instance of a collection containing the elements of a sequence.

init<S>(S)

Creates a new instance of a collection containing the elements of a sequence.

init(Substring.UnicodeScalarView)

Creates a Substring having the given content.

init(Substring.UTF8View)

Creates a Substring having the given content.

init(Substring.UTF16View)

Creates a Substring having the given content.

init(cString: UnsafePointer<CChar>)

Creates a string from the null-terminated, UTF-8 encoded sequence of bytes at the given pointer.

init<C, Encoding>(decoding: C, as: Encoding.Type)

Creates a string from the given Unicode code units in the specified encoding.

init<Encoding>(decodingCString: UnsafePointer<Encoding.CodeUnit>, as: Encoding.Type)

Creates a string from the null-terminated sequence of bytes at the given pointer.

init(extendedGraphemeClusterLiteral: String)

Creates an instance initialized to the given value.

init(repeating: Character, count: Int)

Creates a new collection containing the specified number of a single, repeated value.

init(stringInterpolation: DefaultStringInterpolation)

Creates a new instance from an interpolated string literal.

init(stringLiteral: String)

Creates an instance initialized to the given string value.

init(unicodeScalarLiteral: String)

Creates an instance initialized to the given value.

Instance Properties

var base: String

Returns the underlying string from which this Substring was derived.

var count: Int

The number of elements in the collection.

var customMirror: Mirror

The custom mirror for this instance.

var customPlaygroundQuickLook: _PlaygroundQuickLook

A custom playground Quick Look for this instance.

Deprecated
var debugDescription: String

A textual representation of this instance, suitable for debugging.

var description: String

A textual representation of this instance.

var endIndex: Substring.Index

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

var first: Character?

The first element of the collection.

var hashValue: Int

The hash value.

var indices: DefaultIndices<Substring>

The indices that are valid for subscripting the collection, in ascending order.

var isContiguousUTF8: Bool

Returns whether this string is capable of providing access to validly-encoded UTF-8 contents in contiguous memory in O(1) time.

var isEmpty: Bool

A Boolean value indicating whether the collection is empty.

var last: Character?

The last element of the collection.

var lazy: LazySequence<Substring>

A sequence containing the same elements as this sequence, but on which some operations, such as map and filter, are implemented lazily.

var startIndex: Substring.Index

The position of the first element in a nonempty collection.

var underestimatedCount: Int

A value less than or equal to the number of elements in the collection.

Instance Methods

func allSatisfy((Character) -> Bool) -> Bool

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

func append(Character)

Adds an element to the end of the collection.

func append<S>(contentsOf: S)

Adds the elements of a sequence or collection to the end of this collection.

func append<S>(contentsOf: S)

Adds the elements of a sequence or collection to the end of this collection.

func applying(CollectionDifference<Character>) -> Substring?

Applies the given difference to this collection.

func compactMap<ElementOfResult>((Character) -> ElementOfResult?) -> [ElementOfResult]

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

func contains(Character) -> Bool

Returns a Boolean value indicating whether the sequence contains the given element.

func contains(where: (Character) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

func difference<C>(from: C) -> CollectionDifference<Character>

Returns the difference needed to produce this collection’s ordered elements from the given collection.

func difference<C>(from: C, by: (C.Element, Character) -> Bool) -> CollectionDifference<Character>

Returns the difference needed to produce this collection’s ordered elements from the given collection, using the given predicate as an equivalence test.

func drop(while: (Character) -> Bool) -> Substring

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

func dropFirst(Int) -> Substring

Returns a subsequence containing all but the given number of initial elements.

func dropLast(Int) -> Substring

Returns a subsequence containing all but the specified number of final elements.

func elementsEqual<OtherSequence>(OtherSequence) -> Bool

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

func elementsEqual<OtherSequence>(OtherSequence, by: (Character, OtherSequence.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, using the given predicate as the equivalence test.

func enumerated() -> EnumeratedSequence<Substring>

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

func first(where: (Character) -> Bool) -> Character?

Returns the first element of the sequence that satisfies the given predicate.

func firstIndex(of: Character) -> String.Index?

Returns the first index where the specified value appears in the collection.

func firstIndex(where: (Character) -> Bool) -> String.Index?

Returns the first index in which an element of the collection satisfies the given predicate.

func flatMap<SegmentOfResult>((Character) -> SegmentOfResult) -> [SegmentOfResult.Element]

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

func forEach((Character) -> Void)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

func formIndex(inout String.Index, offsetBy: Int)

Offsets the given index by the specified distance.

func formIndex(inout String.Index, offsetBy: Int, limitedBy: String.Index) -> Bool

Offsets the given index by the specified distance, or so that it equals the given limiting index.

func formIndex(after: inout String.Index)

Replaces the given index with its successor.

func formIndex(before: inout String.Index)

Replaces the given index with its predecessor.

func hasPrefix<Prefix>(Prefix) -> Bool

Returns a Boolean value indicating whether the string begins with the specified prefix.

func hasSuffix<Suffix>(Suffix) -> Bool

Returns a Boolean value indicating whether the string ends with the specified suffix.

func hash(into: inout Hasher)

Hashes the essential components of this value by feeding them into the given hasher.

func index(Substring.Index, offsetBy: Int) -> Substring.Index

Returns an index that is the specified distance from the given index.

func index(Substring.Index, offsetBy: Int, limitedBy: Substring.Index) -> Substring.Index?

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

func index(after: Substring.Index) -> Substring.Index

Returns the position immediately after the given index.

func index(before: Substring.Index) -> Substring.Index

Returns the position immediately before the given index.

func index(of: Character) -> String.Index?

Returns the first index where the specified value appears in the collection.

Deprecated
func index(where: (Character) -> Bool) -> String.Index?

Returns the first index in which an element of the collection satisfies the given predicate.

Deprecated
func insert(Character, at: String.Index)

Inserts a new element into the collection at the specified position.

func insert<C>(contentsOf: C, at: String.Index)

Inserts the elements of a sequence into the collection at the specified position.

func last(where: (Character) -> Bool) -> Character?

Returns the last element of the sequence that satisfies the given predicate.

func lastIndex(of: Character) -> String.Index?

Returns the last index where the specified value appears in the collection.

func lastIndex(where: (Character) -> Bool) -> String.Index?

Returns the index of the last element in the collection that matches the given predicate.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence) -> Bool

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Character, Character) -> Bool) -> Bool

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

func makeContiguousUTF8()

If this string is not contiguous, make it so. If this mutates the substring, it will invalidate any pre-existing indices.

func makeIterator() -> IndexingIterator<Substring>

Returns an iterator over the elements of the collection.

func map<T>((Character) -> T) -> [T]

Returns an array containing the results of mapping the given closure over the sequence’s elements.

func max() -> Character?

Returns the maximum element in the sequence.

func max(by: (Character, Character) -> Bool) -> Character?

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

func min() -> Character?

Returns the minimum element in the sequence.

func min(by: (Character, Character) -> Bool) -> Character?

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

func popFirst() -> Character?

Removes and returns the first element of the collection.

func popLast() -> Character?

Removes and returns the last element of the collection.

func prefix(Int) -> Substring

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

func prefix(through: String.Index) -> Substring

Returns a subsequence from the start of the collection through the specified position.

func prefix(upTo: String.Index) -> Substring

Returns a subsequence from the start of the collection up to, but not including, the specified position.

func prefix(while: (Character) -> Bool) -> Substring

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

func randomElement() -> Character?

Returns a random element of the collection.

func randomElement<T>(using: inout T) -> Character?

Returns a random element of the collection, using the given generator as a source for randomness.

func reduce<Result>(Result, (Result, Character) -> Result) -> Result

Returns the result of combining the elements of the sequence using the given closure.

func reduce<Result>(into: Result, (inout Result, Character) -> ()) -> Result

Returns the result of combining the elements of the sequence using the given closure.

func remove(at: String.Index) -> Character

Removes and returns the element at the specified position.

func removeAll(keepingCapacity: Bool)

Removes all elements from the collection.

func removeAll(where: (Character) -> Bool)

Removes all the elements that satisfy the given predicate.

func removeFirst() -> Character

Removes and returns the first element of the collection.

func removeFirst(Int)

Removes the specified number of elements from the beginning of the collection.

func removeLast() -> Character

Removes and returns the last element of the collection.

func removeLast(Int)

Removes the specified number of elements from the end of the collection.

func removeSubrange(Range<String.Index>)

Removes the elements in the specified subrange from the collection.

func removeSubrange<R>(R)

Removes the elements in the specified subrange from the collection.

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

Replaces the specified subrange of elements with the given collection.

func replaceSubrange<C, R>(R, with: C)

Replaces the specified subrange of elements with the given collection.

func reserveCapacity(Int)

Prepares the collection to store the specified number of elements, when doing so is appropriate for the underlying type.

func reversed() -> ReversedCollection<Substring>

Returns a view presenting the elements of the collection in reverse order.

func shuffled() -> [Character]

Returns the elements of the sequence, shuffled.

func shuffled<T>(using: inout T) -> [Character]

Returns the elements of the sequence, shuffled using the given generator as a source for randomness.

func sorted() -> [Character]

Returns the elements of the sequence, sorted.

func sorted(by: (Character, Character) -> Bool) -> [Character]

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Character) -> Bool) -> [Substring]

Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.

func split(separator: Character, maxSplits: Int, omittingEmptySubsequences: Bool) -> [Substring]

Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.

func starts<PossiblePrefix>(with: PossiblePrefix) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

func starts<PossiblePrefix>(with: PossiblePrefix, by: (Character, PossiblePrefix.Element) -> Bool) -> Bool

Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.

func suffix(Int) -> Substring

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

func suffix(from: String.Index) -> Substring

Returns a subsequence from the specified position to the end of the collection.

func withCString<Result>((UnsafePointer<CChar>) -> Result) -> Result

Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of UTF-8 code units.

func withCString<Result, TargetEncoding>(encodedAs: TargetEncoding.Type, (UnsafePointer<TargetEncoding.CodeUnit>) -> Result) -> Result

Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units.

func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Character>) -> R) -> R?

Call body(p), where p is a pointer to the collection’s contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

func withUTF8<R>((UnsafeBufferPointer<UInt8>) -> R) -> R

Runs body over the content of this substring in contiguous memory. If this substring is not contiguous, this will first make it contiguous, which will also speed up subsequent access. If this mutates the substring, it will invalidate any pre-existing indices.

func write(String)

Appends the given string to the stream.

func write<Target>(to: inout Target)

Writes a textual representation of this instance into the given output stream.

Subscripts

subscript(Substring.Index) -> Character

Accesses the element at the specified position.

subscript(Range<Substring.Index>) -> Substring

Accesses a contiguous subrange of the collection’s elements.

subscript<R>(R) -> Substring

Accesses the contiguous subrange of the collection’s elements specified by a range expression.

Operator Functions

static func != (Substring, Substring) -> Bool

Returns a Boolean value indicating whether two values are not equal.

static func + <Other>(Other, Substring) -> Substring

Creates a new collection by concatenating the elements of a sequence and a collection.

static func + <Other>(Substring, Other) -> Substring

Creates a new collection by concatenating the elements of a collection and a sequence.

static func + <Other>(Substring, Other) -> Substring

Creates a new collection by concatenating the elements of two collections.

static func += <Other>(inout Substring, Other)

Appends the elements of a sequence to a range-replaceable collection.

static func ... (Substring) -> PartialRangeFrom<Substring>

Returns a partial range extending upward from a lower bound.

static func ... (Substring) -> PartialRangeThrough<Substring>

Returns a partial range up to, and including, its upper bound.

static func ... (Substring, Substring) -> ClosedRange<Substring>

Returns a closed range that contains both of its bounds.

static func ..< (Substring) -> PartialRangeUpTo<Substring>

Returns a partial range up to, but not including, its upper bound.

static func ..< (Substring, Substring) -> Range<Substring>

Returns a half-open range that contains its lower bound but not its upper bound.

static func < <RHS>(Substring, RHS) -> Bool

Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.

static func <= (Substring, Substring) -> Bool

Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.

static func <= <RHS>(Substring, RHS) -> Bool

Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.

static func == <RHS>(Substring, RHS) -> Bool

Returns a Boolean value indicating whether two values are equal.

static func > (Substring, Substring) -> Bool

Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.

static func > <RHS>(Substring, RHS) -> Bool

Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.

static func >= (Substring, Substring) -> Bool

Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.

static func >= <RHS>(Substring, RHS) -> Bool

Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.

See Also

Related String Types

protocol StringProtocol

A type that can represent a string as a collection of characters.

struct String.Index

A position of a character or code unit in a string.

struct String.UnicodeScalarView

A view of a string’s contents as a collection of Unicode scalar values.

struct String.UTF16View

A view of a string’s contents as a collection of UTF-16 code units.

struct String.UTF8View

A view of a string’s contents as a collection of UTF-8 code units.

struct String.Iterator

A type that provides the collection’s iteration interface and encapsulates its iteration state.