Structure

Substring

A slice of a string.

Declaration

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

Initializers

init()

Creates an empty substring.

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.CharacterView)

Creates a Substring having the given content.

Deprecated
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(unicodeScalarLiteral: String)

Creates an instance initialized to the given value.

Instance Properties

var count: Int

The number of elements in the collection.

var first: Character?

The first element of the collection.

var indices: DefaultIndices<Substring>

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

var isEmpty: Bool

A Boolean value indicating whether the collection is empty.

var last: Character?

The last element of the collection.

var lazy: LazyCollection<Substring>

A view onto this collection that provides lazy implementations of normally eager operations, such as map and filter.

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 underestimatedCount: Int

A value less than or equal to the number of elements in the sequence, calculated nondestructively.

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 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 drop(while: (Character) -> Bool) -> Substring

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

func dropFirst() -> Substring

Returns a subsequence containing all but the first element of the sequence.

func dropFirst(Int) -> Substring

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

func dropLast() -> Substring

Returns a subsequence containing all but the last element of the sequence.

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 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 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 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 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 popLast() -> Character?

Removes and returns the last 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() -> Character

Removes and returns the first element of the collection.

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 removeFirst(Int)

Removes the specified number of elements from the beginning 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() -> Character

Removes and returns the last element of the collection.

func removeLast() -> Character

Removes and returns the last element of the collection.

func removeLast(Int)

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

func removeLast(Int)

Removes the specified number of elements from the end 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, 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.

Subscripts

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 < <R>(Substring, R) -> 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 <= <R>(Substring, R) -> 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 == <S>(Substring, S) -> 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 > <R>(Substring, R) -> 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 >= <R>(Substring, R) -> 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.