Substring
A slice of a string.
@frozen struct Substring
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
.
Citizens in Swift
Conformances
protocol BidirectionalCollection
A collection that supports backward as well as forward traversal.
protocol Collection
A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.
protocol Comparable
A type that can be compared using the relational operators
<
,<=
,>=
, and>
.protocol CustomDebugStringConvertible
A type with a customized textual representation suitable for debugging purposes.
protocol CustomReflectable
A type that explicitly supplies its own mirror.
protocol CustomStringConvertible
A type with a customized textual representation.
protocol Equatable
A type that can be compared for value equality.
protocol ExpressibleByExtendedGraphemeClusterLiteral
A type that can be initialized with a string literal containing a single extended grapheme cluster.
protocol ExpressibleByStringInterpolation
A type that can be initialized by string interpolation with a string literal that includes expressions.
protocol ExpressibleByStringLiteral
A type that can be initialized with a string literal.
protocol ExpressibleByUnicodeScalarLiteral
A type that can be initialized with a string literal containing a single Unicode scalar value.
protocol Hashable
A type that can be hashed into a
Hasher
to produce an integer hash value.protocol LosslessStringConvertible
A type that can be represented as a string in a lossless, unambiguous way.
protocol RangeReplaceableCollection
A collection that supports replacement of an arbitrary subrange of elements with the elements of another collection.
protocol Sendable
A type whose values can safely be passed across concurrency domains by copying.
protocol Sequence
A type that provides sequential, iterated access to its elements.
protocol StringProtocol
A type that can represent a string as a collection of characters.
protocol TextOutputStream
A type that can be the target of text-streaming operations.
protocol TextOutputStreamable
A source of text-streaming operations.
Members
init(
) Creates an empty substring.
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(String
) init<S>(S
) 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
) init(stringInterpolation: DefaultStringInterpolation
) Creates a new instance from an interpolated string literal.
init(stringLiteral: String
) init(unicodeScalarLiteral: String
) var base: String
Returns the underlying string from which this substring was derived.
var customMirror: Mirror
var debugDescription: String
var description: String
var endIndex: Substring.Index
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 startIndex: Substring.Index
var unicodeScalars: Substring.UnicodeScalarView
var utf16: Substring.UTF16View
var utf8: Substring.UTF8View
subscript(Substring
.Index) -> Character subscript(Range
<Substring.Index>) -> Substring static func ~= (Substring, String
) -> Bool func append<S>(contentsOf: S
) func distance(from: Substring.Index, to: Substring.Index
) -> Int func filter((Substring.Element) throws -> Bool
) rethrows -> String func index(Substring
.Index, offsetBy: Int) -> Substring.Index func index(Substring
.Index, offsetBy: Int, limitedBy: Substring.Index) -> Substring.Index? func index(after: Substring.Index
) -> Substring.Index func index(before: Substring.Index
) -> Substring.Index func lowercased(
) -> String func makeContiguousUTF8(
) If this string is not contiguous, make it so. If this mutates the substring, it will invalidate any pre-existing indices.
func replaceSubrange(Range
<Substring.Index>, with: Substring) func replaceSubrange<C>(Range
<Substring.Index>, with: C) func uppercased(
) -> String func withCString<Result>((UnsafePointer<CChar>) throws -> Result
) rethrows -> 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>) throws -> Result
) rethrows -> Result Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units.
func withUTF8<R>((UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> 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
) func write<Target>(to: inout Target
) struct UTF16View
struct UTF8View
struct UnicodeScalarView
typealias Index
typealias SubSequence
var characters: Substring
A view of the string’s contents as a collection of characters.
var customPlaygroundQuickLook: _PlaygroundQuickLook
func withMutableCharacters<R>((inout Substring) -> R
) -> R Applies the given closure to a mutable view of the string’s characters.
typealias CharacterView
A view of a string’s contents as a collection of characters.
Features
var first: Self.Element?
The first element of the collection.
var last: Self.Element?
The last element of the collection.
var lazy: LazySequence<Self>
A sequence containing the same elements as this sequence, but on which some operations, such as
map
andfilter
, are implemented lazily.static func != (Self, Self
) -> Bool static func != <RHS>(Self, RHS
) -> Bool static func + <Other>(Other, Self
) -> Self Creates a new collection by concatenating the elements of a sequence and a collection.
static func + <Other>(Self, Other
) -> Self Creates a new collection by concatenating the elements of a collection and a sequence.
static func + <Other>(Self, Other
) -> Self Creates a new collection by concatenating the elements of two collections.
static func += <Other>(inout Self, Other
) Appends the elements of a sequence to a range-replaceable collection.
static func ... (Self
) -> PartialRangeFrom<Self> Returns a partial range extending upward from a lower bound.
static func ... (Self
) -> PartialRangeThrough<Self> Returns a partial range up to, and including, its upper bound.
static func ... (Self, Self
) -> ClosedRange<Self> Returns a closed range that contains both of its bounds.
static func ..< (Self
) -> PartialRangeUpTo<Self> Returns a partial range up to, but not including, its upper bound.
static func ..< (Self, Self
) -> Range<Self> Returns a half-open range that contains its lower bound but not its upper bound.
static func == <RHS>(Self, RHS
) -> Bool func allSatisfy((Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
func applying(CollectionDifference
<Self.Element>) -> Self? Applies the given difference to this collection.
func compactMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] Returns an array containing the non-
nil
results of calling the given transformation with each element of this sequence.func contains(Self
.Element) -> Bool Returns a Boolean value indicating whether the sequence contains the given element.
func contains(where: (Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
func difference<C>(from: C
) -> CollectionDifference<Self.Element> Returns the difference needed to produce this collection’s ordered elements from the given collection.
func difference<C>(from: C, by: (C.Element, Self.Element) -> Bool
) -> CollectionDifference<Self.Element> 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: (Self.Element) throws -> Bool
) rethrows -> Self.SubSequence Returns a subsequence by skipping elements while
predicate
returnstrue
and returning the remaining elements.func dropFirst(Int
) -> Self.SubSequence Returns a subsequence containing all but the given number of initial elements.
func dropLast(Int
) -> Self.SubSequence 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: (Self.Element, OtherSequence.Element) throws -> Bool
) rethrows -> 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<Self> 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: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the first element of the sequence that satisfies the given predicate.
func firstIndex(of: Self.Element
) -> Self.Index? Returns the first index where the specified value appears in the collection.
func firstIndex(where: (Self.Element) throws -> Bool
) rethrows -> Self.Index? Returns the first index in which an element of the collection satisfies the given predicate.
func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
func forEach((Self.Element) throws -> Void
) rethrows Calls the given closure on each element in the sequence in the same order as a
for
-in
loop.func formIndex(inout Self
.Index, offsetBy: Int) Offsets the given index by the specified distance.
func formIndex(inout Self
.Index, offsetBy: Int, limitedBy: Self.Index) -> Bool Offsets the given index by the specified distance, or so that it equals the given limiting index.
func last(where: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the last element of the sequence that satisfies the given predicate.
func lastIndex(of: Self.Element
) -> Self.Index? Returns the last index where the specified value appears in the collection.
func lastIndex(where: (Self.Element) throws -> Bool
) rethrows -> Self.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: (Self.Element, Self.Element) throws -> Bool
) rethrows -> 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 map<T>((Self.Element) throws -> T
) rethrows -> [T] Returns an array containing the results of mapping the given closure over the sequence’s elements.
func map<T>((Self.Element) throws -> T
) rethrows -> [T] Returns an array containing the results of mapping the given closure over the sequence’s elements.
func max(
) -> Self.Element? Returns the maximum element in the sequence.
func max(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
func min(
) -> Self.Element? Returns the minimum element in the sequence.
func min(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the minimum element in the sequence, using the given predicate as the comparison between elements.
func popFirst(
) -> Self.Element? Removes and returns the first element of the collection.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func prefix(Int
) -> Self.SubSequence Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.
func prefix(through: Self.Index
) -> Self.SubSequence Returns a subsequence from the start of the collection through the specified position.
func prefix(upTo: Self.Index
) -> Self.SubSequence Returns a subsequence from the start of the collection up to, but not including, the specified position.
func prefix(while: (Self.Element) throws -> Bool
) rethrows -> Self.SubSequence Returns a subsequence containing the initial elements until
predicate
returnsfalse
and skipping the remaining elements.func randomElement(
) -> Self.Element? Returns a random element of the collection.
func randomElement<T>(using: inout T
) -> Self.Element? Returns a random element of the collection, using the given generator as a source for randomness.
func reduce<Result>(Result, (Result, Self.Element) throws -> Result
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func reduce<Result>(into: Result, (inout Result, Self.Element) throws -> ()
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func removeFirst(
) -> Self.Element 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(
) -> Self.Element Removes and returns the last element of the collection.
func removeLast(
) -> Self.Element Removes and returns the last element of the collection.
func removeLast(
) -> Self.Element 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 reversed(
) -> ReversedCollection<Self> Returns a view presenting the elements of the collection in reverse order.
func shuffled(
) -> [Self.Element] Returns the elements of the sequence, shuffled.
func shuffled<T>(using: inout T
) -> [Self.Element] Returns the elements of the sequence, shuffled using the given generator as a source for randomness.
func sorted(
) -> [Self.Element] Returns the elements of the sequence, sorted.
func sorted(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> [Self.Element] Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Self.Element) throws -> Bool
) rethrows -> [Self.SubSequence] Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.
func split(separator: Self.Element, maxSplits: Int, omittingEmptySubsequences: Bool
) -> [Self.SubSequence] 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: (Self.Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> 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
) -> Self.SubSequence Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
func suffix(from: Self.Index
) -> Self.SubSequence Returns a subsequence from the specified position to the end of the collection.
func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] func index(of: Self.Element
) -> Self.Index? Returns the first index where the specified value appears in the collection.
Available in RegexBuilder
Conformances
protocol RegexComponent
A type that represents a regular expression.
Members
Extension in JSONEncoding
Conformances
protocol JSONEncodable
A type that can be encoded to a JSON variant value.
Members
func encoded(as: JSON.Type
) -> JSON Encodes this substring as a value of
JSON.string(_:)
.
Extension in BSONEncoding
Conformances
protocol BSONEncodable
A type that can be encoded to a BSON variant value.
Members
func encode(to: inout BSON.Field
) Encodes this substring as a value of type
BSON.string
.
Extension in SwiftSyntaxBuilder
Conformances
protocol ExpressibleByLiteralSyntax
A Swift type whose value can be represented directly in source code by a Swift literal.