<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Substring",
  "metadataVersion" : "0.1.0",
  "role" : "Structure",
  "symbol" : {
    "kind" : "Structure",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Ss"
  },
  "title" : "Substring"
}
-->

# Substring

A slice of a string.

```
@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`.

> Important: Don’t store substrings longer than you need them to perform a
> specific operation. A substring holds a reference to the entire storage
> of the string it comes from, not just to the portion it presents, even
> when there is no other reference to the original string. Storing
> substrings may, therefore, prolong the lifetime of string data that is
> no longer otherwise accessible, which can appear to be memory leakage.

## Topics

### Operators

[`static func ~= (Substring, String) -> Bool`](/documentation/Swift/Substring/~=(_:_:))

### Initializers

[`init()`](/documentation/Swift/Substring/init())

Creates an empty substring.

[`init(Substring.UTF8View)`](/documentation/Swift/Substring/init(_:)-4njms)

Creates a Substring having the given content.

[`init(Substring.UTF16View)`](/documentation/Swift/Substring/init(_:)-61zpv)

Creates a Substring having the given content.

[`init(Substring.UnicodeScalarView)`](/documentation/Swift/Substring/init(_:)-7k0au)

Creates a Substring having the given content.

### Instance Properties

[`var base: String`](/documentation/Swift/Substring/base)

Returns the underlying string from which this substring was derived.

[`var characters: Substring`](/documentation/Swift/Substring/characters)

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

[`var customPlaygroundQuickLook: _PlaygroundQuickLook`](/documentation/Swift/Substring/customPlaygroundQuickLook)

A custom playground Quick Look for this instance.

[`var isContiguousUTF8: Bool`](/documentation/Swift/Substring/isContiguousUTF8)

Returns whether this string’s storage contains
validly-encoded UTF-8 contents in contiguous memory.

[`var utf8Span: UTF8Span`](/documentation/Swift/Substring/utf8Span)

A UTF-8 span over the code units that make up this substring.

### Instance Methods

[`func filter<E>((Substring.Element) throws(E) -> Bool) throws(E) -> String`](/documentation/Swift/Substring/filter(_:))

[`func isTriviallyIdentical(to: Substring) -> Bool`](/documentation/Swift/Substring/isTriviallyIdentical(to:))

Returns a boolean value indicating whether this substring is identical to
`other`.

[`func makeContiguousUTF8()`](/documentation/Swift/Substring/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)`](/documentation/Swift/Substring/replaceSubrange(_:with:)-mfwu)

[`func withMutableCharacters<R>((inout Substring) -> R) -> R`](/documentation/Swift/Substring/withMutableCharacters(_:))

Applies the given closure to a mutable view of the string’s characters.

[`func withUTF8<R, E>((UnsafeBufferPointer<UInt8>) throws(E) -> R) throws(E) -> R`](/documentation/Swift/Substring/withUTF8(_:))

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.

### Type Aliases

[`typealias CharacterView`](/documentation/Swift/Substring/CharacterView)

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

[`typealias Output`](/documentation/Swift/Substring/Output)

### Default Implementations

[Attachable Implementations](/documentation/Swift/Substring/Attachable-Implementations)

[BidirectionalCollection Implementations](/documentation/Swift/Substring/BidirectionalCollection-Implementations)

[Collection Implementations](/documentation/Swift/Substring/Collection-Implementations)

[Comparable Implementations](/documentation/Swift/Substring/Comparable-Implementations)

[CustomDebugStringConvertible Implementations](/documentation/Swift/Substring/CustomDebugStringConvertible-Implementations)

[CustomReflectable Implementations](/documentation/Swift/Substring/CustomReflectable-Implementations)

[CustomStringConvertible Implementations](/documentation/Swift/Substring/CustomStringConvertible-Implementations)

[Equatable Implementations](/documentation/Swift/Substring/Equatable-Implementations)

[ExpressibleByExtendedGraphemeClusterLiteral Implementations](/documentation/Swift/Substring/ExpressibleByExtendedGraphemeClusterLiteral-Implementations)

[ExpressibleByStringInterpolation Implementations](/documentation/Swift/Substring/ExpressibleByStringInterpolation-Implementations)

[ExpressibleByStringLiteral Implementations](/documentation/Swift/Substring/ExpressibleByStringLiteral-Implementations)

[ExpressibleByUnicodeScalarLiteral Implementations](/documentation/Swift/Substring/ExpressibleByUnicodeScalarLiteral-Implementations)

[Hashable Implementations](/documentation/Swift/Substring/Hashable-Implementations)

[LosslessStringConvertible Implementations](/documentation/Swift/Substring/LosslessStringConvertible-Implementations)

[RangeReplaceableCollection Implementations](/documentation/Swift/Substring/RangeReplaceableCollection-Implementations)

[Sequence Implementations](/documentation/Swift/Substring/Sequence-Implementations)

[StringProtocol Implementations](/documentation/Swift/Substring/StringProtocol-Implementations)

[TextOutputStream Implementations](/documentation/Swift/Substring/TextOutputStream-Implementations)

[TextOutputStreamable Implementations](/documentation/Swift/Substring/TextOutputStreamable-Implementations)

## Relationships

### Conforms To

[`ExpressibleByStringLiteral`](/documentation/Swift/ExpressibleByStringLiteral)

[`Attachable`](/documentation/Testing/Attachable)

[`RegexComponent`](/documentation/Swift/RegexComponent)

[`Sequence`](/documentation/Swift/Sequence)

[`SendableMetatype`](/documentation/Swift/SendableMetatype)

[`CustomDebugStringConvertible`](/documentation/Swift/CustomDebugStringConvertible)

[`RangeReplaceableCollection`](/documentation/Swift/RangeReplaceableCollection)

[`CustomReflectable`](/documentation/Swift/CustomReflectable)

[`ExpressibleByUnicodeScalarLiteral`](/documentation/Swift/ExpressibleByUnicodeScalarLiteral)

[`StringProtocol`](/documentation/Swift/StringProtocol)

[`Hashable`](/documentation/Swift/Hashable)

[`TextOutputStreamable`](/documentation/Swift/TextOutputStreamable)

[`Copyable`](/documentation/Swift/Copyable)

[`Equatable`](/documentation/Swift/Equatable)

[`CustomStringConvertible`](/documentation/Swift/CustomStringConvertible)

[`BidirectionalCollection`](/documentation/Swift/BidirectionalCollection)

[`Collection`](/documentation/Swift/Collection)

[`CustomTestStringConvertible`](/documentation/Testing/CustomTestStringConvertible)

[`Sendable`](/documentation/Swift/Sendable)

[`ExpressibleByStringInterpolation`](/documentation/Swift/ExpressibleByStringInterpolation)

[`ExpressibleByExtendedGraphemeClusterLiteral`](/documentation/Swift/ExpressibleByExtendedGraphemeClusterLiteral)

[`TextOutputStream`](/documentation/Swift/TextOutputStream)

[`Escapable`](/documentation/Swift/Escapable)

[`Comparable`](/documentation/Swift/Comparable)

[`LosslessStringConvertible`](/documentation/Swift/LosslessStringConvertible)

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)