String

struct String

A Unicode string value that is a collection of characters.

Inheritance BidirectionalCollection, Codable, Comparable, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByStringLiteral, Hashable, RangeReplaceableCollection, TextOutputStream, TextOutputStreamable
Associated Types
public typealias UnicodeScalarIndex = String.UnicodeScalarView.Index
public typealias IndexDistance = Int

In Swift, reachability refers to the ability to produce one value from the other through zero or more applications of index(after:).

public typealias SubSequence = Substring

This associated type appears as a requirement in the Sequence protocol, but it is restated here with stricter constraints. In a collection, the subsequence should also conform to Collection.

public typealias Element = Character
Nested Types String.Iterator, String.Index, String.UnicodeScalarView, String.UTF16View, String.UTF8View

A string is a series of characters, such as "Swift", that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

You can create new strings using string literals or string interpolations. A string literal is a series of characters enclosed in quotes.

let greeting = "Welcome!"

String interpolations are string literals that evaluate any included expressions and convert the results to string form. String interpolations give you an easy way to build a string from multiple pieces. Wrap each expression in a string interpolation in parentheses, prefixed by a backslash.

let name = "Rosa"
let personalizedGreeting = "Welcome, \(name)!"
// personalizedGreeting == "Welcome, Rosa!"

let price = 2
let number = 3
let cookiePrice = "\(number) cookies: $\(price * number)."
// cookiePrice == "3 cookies: $6."

Combine strings using the concatenation operator (+).

let longerGreeting = greeting + " We're glad you're here!"
// longerGreeting == "Welcome! We're glad you're here!"

Multiline string literals are enclosed in three double quotation marks ("""), with each delimiter on its own line. Indentation is stripped from each line of a multiline string literal to match the indentation of the closing delimiter.

let banner = """
          __,
         (           o  /) _/_
          `.  , , , ,  //  /
        (___)(_(_/_(_ //_ (__
                     /)
                    (/
        """

Modifying and Comparing Strings

Strings always have value semantics. Modifying a copy of a string leaves the original unaffected.

var otherGreeting = greeting
otherGreeting += " Have a nice time!"
// otherGreeting == "Welcome! Have a nice time!"

print(greeting)
// Prints "Welcome!"

Comparing strings for equality using the equal-to operator (==) or a relational operator (like < or >=) is always performed using Unicode canonical representation. As a result, different representations of a string compare as being equal.

let cafe1 = "Cafe\u{301}"
let cafe2 = "Café"
print(cafe1 == cafe2)
// Prints "true"

The Unicode scalar value "\u{301}" modifies the preceding character to include an accent, so "e\u{301}" has the same canonical representation as the single Unicode scalar value "é".

Basic string operations are not sensitive to locale settings, ensuring that string comparisons and other operations always have a single, stable result, allowing strings to be used as keys in Dictionary instances and for other purposes.

Accessing String Elements

A string is a collection of extended grapheme clusters, which approximate human-readable characters. Many individual characters, such as "é", "김", and "🇮🇳", can be made up of multiple Unicode scalar values. These scalar values are combined by Unicode's boundary algorithms into extended grapheme clusters, represented by the Swift Character type. Each element of a string is represented by a Character instance.

For example, to retrieve the first word of a longer string, you can search for a space and then create a substring from a prefix of the string up to that point:

let name = "Marie Curie"
let firstSpace = name.firstIndex(of: " ") ?? name.endIndex
let firstName = name[..<firstSpace]
// firstName == "Marie"

The firstName constant is an instance of the Substring type---a type that represents substrings of a string while sharing the original string's storage. Substrings present the same interface as strings.

print("\(name)'s first name has \(firstName.count) letters.")
// Prints "Marie Curie's first name has 5 letters."

Accessing a String's Unicode Representation

If you need to access the contents of a string as encoded in different Unicode encodings, use one of the string's unicodeScalars, utf16, or utf8 properties. Each property provides access to a view of the string as a series of code units, each encoded in a different Unicode encoding.

To demonstrate the different views available for every string, the following examples use this String instance:

let cafe = "Cafe\u{301} du 🌍"
print(cafe)
// Prints "Café du 🌍"

The cafe string is a collection of the nine characters that are visible when the string is displayed.

print(cafe.count)
// Prints "9"
print(Array(cafe))
// Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]"

Unicode Scalar View

A string's unicodeScalars property is a collection of Unicode scalar values, the 21-bit codes that are the basic unit of Unicode. Each scalar value is represented by a Unicode.Scalar instance and is equivalent to a UTF-32 code unit.

print(cafe.unicodeScalars.count)
// Prints "10"
print(Array(cafe.unicodeScalars))
// Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]"
print(cafe.unicodeScalars.map { $0.value })
// Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]"

The unicodeScalars view's elements comprise each Unicode scalar value in the cafe string. In particular, because cafe was declared using the decomposed form of the "é" character, unicodeScalars contains the scalar values for both the letter "e" (101) and the accent character "´" (769).

UTF-16 View

A string's utf16 property is a collection of UTF-16 code units, the 16-bit encoding form of the string's Unicode scalar values. Each code unit is stored as a UInt16 instance.

print(cafe.utf16.count)
// Prints "11"
print(Array(cafe.utf16))
// Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]"

The elements of the utf16 view are the code units for the string when encoded in UTF-16. These elements match those accessed through indexed NSString APIs.

let nscafe = cafe as NSString
print(nscafe.length)
// Prints "11"
print(nscafe.character(at: 3))
// Prints "101"

UTF-8 View

A string's utf8 property is a collection of UTF-8 code units, the 8-bit encoding form of the string's Unicode scalar values. Each code unit is stored as a UInt8 instance.

print(cafe.utf8.count)
// Prints "14"
print(Array(cafe.utf8))
// Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"

The elements of the utf8 view are the code units for the string when encoded in UTF-8. This representation matches the one used when String instances are passed to C APIs.

let cLength = strlen(cafe)
print(cLength)
// Prints "14"

Measuring the Length of a String

When you need to know the length of a string, you must first consider what you'll use the length for. Are you measuring the number of characters that will be displayed on the screen, or are you measuring the amount of storage needed for the string in a particular encoding? A single string can have greatly differing lengths when measured by its different views.

For example, an ASCII character like the capital letter A is represented by a single element in each of its four views. The Unicode scalar value of A is 65, which is small enough to fit in a single code unit in both UTF-16 and UTF-8.

let capitalA = "A"
print(capitalA.count)
// Prints "1"
print(capitalA.unicodeScalars.count)
// Prints "1"
print(capitalA.utf16.count)
// Prints "1"
print(capitalA.utf8.count)
// Prints "1"

On the other hand, an emoji flag character is constructed from a pair of Unicode scalar values, like "\u{1F1F5}" and "\u{1F1F7}". Each of these scalar values, in turn, is too large to fit into a single UTF-16 or UTF-8 code unit. As a result, each view of the string "🇵🇷" reports a different length.

let flag = "🇵🇷"
print(flag.count)
// Prints "1"
print(flag.unicodeScalars.count)
// Prints "2"
print(flag.utf16.count)
// Prints "4"
print(flag.utf8.count)
// Prints "8"

To check whether a string is empty, use its isEmpty property instead of comparing the length of one of the views to 0. Unlike with isEmpty, calculating a view's count property requires iterating through the elements of the string.

Accessing String View Elements

To find individual elements of a string, use the appropriate view for your task. For example, to retrieve the first word of a longer string, you can search the string for a space and then create a new string from a prefix of the string up to that point.

let name = "Marie Curie"
let firstSpace = name.firstIndex(of: " ") ?? name.endIndex
let firstName = name[..<firstSpace]
print(firstName)
// Prints "Marie"

Strings and their views share indices, so you can access the UTF-8 view of the name string using the same firstSpace index.

print(Array(name.utf8[..<firstSpace]))
// Prints "[77, 97, 114, 105, 101]"

Note that an index into one view may not have an exact corresponding position in another view. For example, the flag string declared above comprises a single character, but is composed of eight code units when encoded as UTF-8. The following code creates constants for the first and second positions in the flag.utf8 view. Accessing the utf8 view with these indices yields the first and second code UTF-8 units.

let firstCodeUnit = flag.startIndex
let secondCodeUnit = flag.utf8.index(after: firstCodeUnit)
// flag.utf8[firstCodeUnit] == 240
// flag.utf8[secondCodeUnit] == 159

When used to access the elements of the flag string itself, however, the secondCodeUnit index does not correspond to the position of a specific character. Instead of only accessing the specific UTF-8 code unit, that index is treated as the position of the character at the index's encoded offset. In the case of secondCodeUnit, that character is still the flag itself.

// flag[firstCodeUnit] == "🇵🇷"
// flag[secondCodeUnit] == "🇵🇷"

If you need to validate that an index from one string's view corresponds with an exact position in another view, use the index's samePosition(in:) method or the init(_:within:) initializer.

if let exactIndex = secondCodeUnit.samePosition(in: flag) {
    print(flag[exactIndex])
} else {
    print("No exact match for this position.")
}
// Prints "No exact match for this position."

Performance Optimizations

Although strings in Swift have value semantics, strings use a copy-on-write strategy to store their data in a buffer. This buffer can then be shared by different copies of a string. A string's data is only copied lazily, upon mutation, when more than one string instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost O(n) time and space.

When a string's contiguous storage fills up, a new buffer must be allocated and data must be moved to the new storage. String buffers use an exponential growth strategy that makes appending to a string a constant time operation when averaged over many append operations.

Bridging Between String and NSString

Any String instance can be bridged to NSString using the type-cast operator (as), and any String instance that originates in Objective-C may use an NSString instance as its storage. Because any arbitrary subclass of NSString can become a String instance, there are no guarantees about representation or efficiency when a String instance is backed by NSString storage. Because NSString is immutable, it is just as though the storage was shared by a copy. The first in any sequence of mutating operations causes elements to be copied into unique, contiguous storage which may cost O(n) time and space, where n is the length of the string's encoded representation (or more, if the underlying NSString has unusual performance characteristics).

For more information about the Unicode terms used in this discussion, see the Unicode.org glossary. In particular, this discussion mentions extended grapheme clusters, Unicode scalar values, and canonical equivalence.

Initializers

init init() Required

Creates an empty string.

Using this initializer is equivalent to initializing a string with an empty string literal.

let empty = ""
let alsoEmpty = String()

Declaration

@inlinable public init()
init init(_:) Required

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

  • Parameter elements: The sequence of elements for the new collection.

Declaration

@inlinable public init<S>(_ elements: S) where S: Sequence, Self.Element == S.Element
init init(_:) Required

Creates a string containing the given character.

  • Parameter c: The character to convert to a string.

Declaration

@inlinable public init(_ c: Character)
init init(_:) Required

Declaration

@inlinable public init(_ scalar: Unicode.Scalar)
init init(_:) Required

Creates an instance from the description of a given LosslessStringConvertible instance.

Declaration

@inlinable public init<T>(_ value: T) where T: LosslessStringConvertible
init init(_:) Required

Creates a string corresponding to the given collection of Unicode scalars.

You can use this initializer to create a new string from a slice of another string's unicodeScalars view.

let picnicGuest = "Deserving porcupine"
if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") {
    let adjective = String(picnicGuest.unicodeScalars[..<i])
    print(adjective)
}
// Prints "Deserving"

The adjective constant is created by calling this initializer with a slice of the picnicGuest.unicodeScalars view.

  • Parameter unicodeScalars: A collection of Unicode scalar values.

Declaration

@inlinable public init(_ unicodeScalars: String.UnicodeScalarView)
init init(_:) Required

Creates a string corresponding to the given sequence of UTF-16 code units.

Declaration

@available(swift 4.0) @inlinable public init(_ utf16: String.UTF16View)
init init(_:) Required

Creates a string corresponding to the given sequence of UTF-8 code units.

Declaration

@available(swift, introduced: 4.0, message: "Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode") @inlinable public init(_ utf8: String.UTF8View)
init init(_:) Required

Creates a new string from the given substring.

  • Parameter substring: A substring to convert to a standalone String instance.

Complexity: O(n), where n is the length of substring.

Declaration

@inlinable public init(_ substring: Substring)
init init(_:) Required

Creates a String having the given content.

Complexity: O(N), where N is the length of the resulting String's UTF-16.

Declaration

public init(_ content: Substring.UnicodeScalarView)
init init(_:) Required

Creates a new string containing the characters in the given sequence.

You can use this initializer to create a new string from the result of one or more collection operations on a string's characters. For example:

let str = "The rain in Spain stays mainly in the plain."

let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
let disemvoweled = String(str.lazy.filter { !vowels.contains($0) })

print(disemvoweled)
// Prints "Th rn n Spn stys mnly n th pln."
  • Parameter other: A string instance or another sequence of characters.

Declaration

public init<S>(_ other: S) where S: LosslessStringConvertible, S: Sequence, S.Element == Character
init init(_:) Required

Creates a new string containing the characters in the given sequence.

You can use this initializer to create a new string from the result of one or more collection operations on a string's characters. For example:

let str = "The rain in Spain stays mainly in the plain."

let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
let disemvoweled = String(str.lazy.filter { !vowels.contains($0) })

print(disemvoweled)
// Prints "Th rn n Spn stys mnly n th pln."
  • Parameter characters: A string instance or another sequence of characters.

Declaration

public init<S>(_ characters: S) where S: Sequence, S.Element == Character
init init(_:radix:uppercase:) Required

Creates a string representing the given value in base 10, or some other specified base.

The following example converts the maximal Int value to a string and prints its length:

let max = String(Int.max)
print("\(max) has \(max.count) digits.")
// Prints "9223372036854775807 has 19 digits."

Numerals greater than 9 are represented as Roman letters. These letters start with "A" if uppercase is true; otherwise, with "a".

let v = 999_999
print(String(v, radix: 2))
// Prints "11110100001000111111"

print(String(v, radix: 16))
// Prints "f423f"
print(String(v, radix: 16, uppercase: true))
// Prints "F423F"

Declaration

public init<T>(_ value: T, radix: Int = 10, uppercase: Bool = false) where T: BinaryInteger
init init(cString:) Required

Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.

If cString contains ill-formed UTF-8 code unit sequences, this initializer replaces them with the Unicode replacement character ("\u{FFFD}").

The following example calls this initializer with pointers to the contents of two different CChar arrays---the first with well-formed UTF-8 code unit sequences and the second with an ill-formed sequence at the end.

let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
validUTF8.withUnsafeBufferPointer { ptr in
    let s = String(cString: ptr.baseAddress!)
    print(s)
}
// Prints "Café"

let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
invalidUTF8.withUnsafeBufferPointer { ptr in
    let s = String(cString: ptr.baseAddress!)
    print(s)
}
// Prints "Caf�"
  • Parameter cString: A pointer to a null-terminated UTF-8 code sequence.

Declaration

public init(cString: UnsafePointer<CChar>)
init init(cString:) Required

Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.

This is identical to init(cString: UnsafePointer<CChar>) but operates on an unsigned sequence of bytes.

Declaration

public init(cString: UnsafePointer<UInt8>)
init init(decoding:as:) Required

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

Declaration

@inlinable public init<C, Encoding>(decoding codeUnits: C, as sourceEncoding: Encoding.Type) where C: Collection, Encoding: _UnicodeEncoding, C.Element == Encoding.CodeUnit
init init(decodingCString:as:) Required

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

Declaration

@inlinable public init<Encoding>(decodingCString ptr: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type) where Encoding: _UnicodeEncoding
init init(describing:) Required

Creates a string representing the given value.

Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:

For example, this custom Point struct uses the default representation supplied by the standard library.

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(describing: p))
// Prints "Point(x: 21, y: 30)"

After adding CustomStringConvertible conformance by implementing the description property, Point provides its own custom representation.

extension Point: CustomStringConvertible {
    var description: String {
        return "(\(x), \(y))"
    }
}

print(String(describing: p))
// Prints "(21, 30)"

Declaration

public init<Subject>(describing instance: Subject)
init init(describing:) Required

Creates a string representing the given value.

Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:

For example, this custom Point struct uses the default representation supplied by the standard library.

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(describing: p))
// Prints "Point(x: 21, y: 30)"

After adding CustomStringConvertible conformance by implementing the description property, Point provides its own custom representation.

extension Point: CustomStringConvertible {
    var description: String {
        return "(\(x), \(y))"
    }
}

print(String(describing: p))
// Prints "(21, 30)"

Declaration

@inlinable public init<Subject>(describing instance: Subject) where Subject: CustomStringConvertible
init init(describing:) Required

Creates a string representing the given value.

Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:

For example, this custom Point struct uses the default representation supplied by the standard library.

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(describing: p))
// Prints "Point(x: 21, y: 30)"

After adding CustomStringConvertible conformance by implementing the description property, Point provides its own custom representation.

extension Point: CustomStringConvertible {
    var description: String {
        return "(\(x), \(y))"
    }
}

print(String(describing: p))
// Prints "(21, 30)"

Declaration

@inlinable public init<Subject>(describing instance: Subject) where Subject: TextOutputStreamable
init init(describing:) Required

Creates a string representing the given value.

Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:

For example, this custom Point struct uses the default representation supplied by the standard library.

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(describing: p))
// Prints "Point(x: 21, y: 30)"

After adding CustomStringConvertible conformance by implementing the description property, Point provides its own custom representation.

extension Point: CustomStringConvertible {
    var description: String {
        return "(\(x), \(y))"
    }
}

print(String(describing: p))
// Prints "(21, 30)"

Declaration

@inlinable public init<Subject>(describing instance: Subject) where Subject: CustomStringConvertible, Subject: TextOutputStreamable
init init(from:) Required

Creates a new instance by decoding from the given decoder.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

  • Parameter decoder: The decoder to read data from.

Declaration

public init(from decoder: Decoder) throws
init init(reflecting:) Required

Creates a string with a detailed representation of the given value, suitable for debugging.

Use this initializer to convert an instance of any type to its custom debugging representation. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance:

For example, this custom Point struct uses the default representation supplied by the standard library.

struct Point {
    let x: Int, y: Int
}

let p = Point(x: 21, y: 30)
print(String(reflecting: p))
// Prints "p: Point = {
//           x = 21
//           y = 30
//         }"

After adding CustomDebugStringConvertible conformance by implementing the debugDescription property, Point provides its own custom debugging representation.

extension Point: CustomDebugStringConvertible {
    var debugDescription: String {
        return "Point(x: \(x), y: \(y))"
    }
}

print(String(reflecting: p))
// Prints "Point(x: 21, y: 30)"

Declaration

public init<Subject>(reflecting subject: Subject)
init init(repeating:count:) Required

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

Here's an example of creating an array initialized with five strings containing the letter Z.

let fiveZs = Array(repeating: "Z", count: 5)
print(fiveZs)
// Prints "["Z", "Z", "Z", "Z", "Z"]"

Declaration

@inlinable public init(repeating repeatedValue: Self.Element, count: Int)
init init(repeating:count:) Required

Creates a new string representing the given string repeated the specified number of times.

For example, you can use this initializer to create a string with ten "ab" strings in a row.

let s = String(repeating: "ab", count: 10)
print(s)
// Prints "abababababababababab"

Declaration

public init(repeating repeatedValue: String, count: Int)
init init(repeating:count:) Required

Creates a string representing the given character repeated the specified number of times.

For example, use this initializer to create a string with ten "0" characters in a row.

let zeroes = String(repeating: "0" as Character, count: 10)
print(zeroes)
// Prints "0000000000"

Declaration

public init(repeating repeatedValue: Character, count: Int)
init init(stringInterpolation:) Required

Creates a new instance from an interpolated string literal.

Do not call this initializer directly. It is used by the compiler when you create a string using string interpolation. Instead, use string interpolation to create a new string by including values, literals, variables, or expressions enclosed in parentheses, prefixed by a backslash (\(...)).

let price = 2
let number = 3
let message = """
              If one cookie costs \(price) dollars, \
              \(number) cookies cost \(price * number) dollars.
              """
print(message)
// Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."

Declaration

@inlinable public init(stringInterpolation: DefaultStringInterpolation)
init init(stringLiteral:) Required

Creates an instance initialized to the given string value.

Do not call this initializer directly. It is used by the compiler when you initialize a string using a string literal. For example:

let nextStop = "Clark & Lake"

This assignment to the nextStop constant calls this string literal initializer behind the scenes.

Declaration

@inlinable public init(stringLiteral value: String)
init init?(_:) Required

Creates a String having the given content.

If codeUnits is an ill-formed code unit sequence, the result is nil.

Complexity: O(N), where N is the length of the resulting String's UTF-16.

Declaration

public init?(_ codeUnits: Substring.UTF8View)
init init?(_:) Required

Creates a String having the given content.

If codeUnits is an ill-formed code unit sequence, the result is nil.

Complexity: O(N), where N is the length of the resulting String's UTF-16.

Declaration

public init?(_ codeUnits: Substring.UTF16View)
init init?(validatingUTF8:) Required

Creates a new string by copying and validating the null-terminated UTF-8 data referenced by the given pointer.

This initializer does not try to repair ill-formed UTF-8 code unit sequences. If any are found, the result of the initializer is nil.

The following example calls this initializer with pointers to the contents of two different CChar arrays---the first with well-formed UTF-8 code unit sequences and the second with an ill-formed sequence at the end.

let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
validUTF8.withUnsafeBufferPointer { ptr in
    let s = String(validatingUTF8: ptr.baseAddress!)
    print(s)
}
// Prints "Optional(Café)"

let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
invalidUTF8.withUnsafeBufferPointer { ptr in
    let s = String(validatingUTF8: ptr.baseAddress!)
    print(s)
}
// Prints "nil"
  • Parameter cString: A pointer to a null-terminated UTF-8 code sequence.

Declaration

public init?(validatingUTF8 cString: UnsafePointer<CChar>)

Instance Variables

var count Required

The number of characters in a string.

Declaration

var count: Int
var customMirror Required

A mirror that reflects the String instance.

Declaration

var customMirror: Mirror
var customPlaygroundQuickLook Required

A custom playground Quick Look for the String instance.

Declaration

var customPlaygroundQuickLook: _PlaygroundQuickLook
var debugDescription Required

A representation of the string that is suitable for debugging.

Declaration

var debugDescription: String
var description Required

The value of this string.

Using this property directly is discouraged. Instead, use simple assignment to create a new constant or variable equal to this string.

Declaration

var description: String
var endIndex Required

A string's "past the end" position---that is, the position one greater than the last valid subscript argument.

In an empty string, endIndex is equal to startIndex.

Declaration

var endIndex: String.Index
var isContiguousUTF8 Required

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

Contiguous strings always operate in O(1) time for withUTF8 and always give a result for String.UTF8View.withContiguousStorageIfAvailable. Contiguous strings also benefit from fast-paths and better optimizations.

Declaration

var isContiguousUTF8: Bool
var isEmpty Required

A Boolean value indicating whether a string has no characters.

Declaration

var isEmpty: Bool
var last Required

The last element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let lastNumber = numbers.last {
    print(lastNumber)
}
// Prints "50"

Complexity: O(1)

Declaration

var last: Self.Element?
var startIndex Required

The position of the first character in a nonempty string.

In an empty string, startIndex is equal to endIndex.

Declaration

var startIndex: String.Index
var unicodeScalars Required

The string's value represented as a collection of Unicode scalar values.

Declaration

var unicodeScalars: String.UnicodeScalarView
var utf16 Required

A UTF-16 encoding of self.

Declaration

var utf16: String.UTF16View
var utf8 Required

A UTF-8 encoding of self.

Declaration

var utf8: String.UTF8View
var utf8CString Required

A contiguously stored null-terminated UTF-8 representation of the string.

To access the underlying memory, invoke withUnsafeBufferPointer on the array.

let s = "Hello!"
let bytes = s.utf8CString
print(bytes)
// Prints "[72, 101, 108, 108, 111, 33, 0]"

bytes.withUnsafeBufferPointer { ptr in
    print(strlen(ptr.baseAddress!))
}
// Prints "6"

Declaration

var utf8CString: ContiguousArray<CChar>

Subscripts

subscript subscript(i:) Required

Accesses the character at the given position.

You can use the same indices for subscripting a string and its substring. For example, this code finds the first letter after the first space:

let str = "Greetings, friend! How are you?"
let firstSpace = str.firstIndex(of: " ") ?? str.endIndex
let substr = str[firstSpace...]
if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) {
    print("Capital after a space: \(str[nextCapital])")
}
// Prints "Capital after a space: H"
  • Parameter i: A valid index of the string. i must be less than the string's end index.

Declaration

@inlinable public subscript(i: String.Index) -> Character
subscript subscript(r:) Required

Accesses a contiguous subrange of the collection's elements.

The accessed slice uses the same indices for the same elements as the original collection uses. Always use the slice's startIndex property instead of assuming that its indices start at a particular value.

This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print(streetsSlice)
// Prints "["Channing", "Douglas", "Evarts"]"

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// Prints "Evarts"
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@available(swift 4) @inlinable public subscript(r: Range<String.Index>) -> Substring

Instance Methods

func append(_ newElement: Self.Element) Required

Adds an element to the end of the collection.

If the collection does not have sufficient capacity for another element, additional storage is allocated before appending newElement. The following example adds a new number to an array of integers:

var numbers = [1, 2, 3, 4, 5]
numbers.append(100)

print(numbers)
// Prints "[1, 2, 3, 4, 5, 100]"
  • Parameter newElement: The element to append to the collection.

Complexity: O(1) on average, over many calls to append(_:) on the same collection.

Declaration

@inlinable public mutating func append(_ newElement: Self.Element)
func append(_ other: String) Required

Appends the given string to this string.

The following example builds a customized greeting by using the append(_:) method:

var greeting = "Hello, "
if let name = getUserName() {
    greeting.append(name)
} else {
    greeting.append("friend")
}
print(greeting)
// Prints "Hello, friend"
  • Parameter other: Another string.

Declaration

public mutating func append(_ other: String)
func append(_ c: Character) Required

Appends the given character to the string.

The following example adds an emoji globe to the end of a string.

var globe = "Globe "
globe.append("🌍")
print(globe)
// Prints "Globe 🌍"
  • Parameter c: The character to append to the string.

Declaration

public mutating func append(_ c: Character)
func append(contentsOf newElements: S) Required

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

The collection being appended to allocates any additional necessary storage to hold the new elements.

The following example appends the elements of a Range<Int> instance to an array of integers:

var numbers = [1, 2, 3, 4, 5]
numbers.append(contentsOf: 10...15)
print(numbers)
// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
  • Parameter newElements: The elements to append to the collection.

Complexity: O(m), where m is the length of newElements.

Declaration

@inlinable public mutating func append<S>(contentsOf newElements: S) where S: Sequence, Self.Element == S.Element
func append(contentsOf newElements: String) Required

Declaration

public mutating func append(contentsOf newElements: String)
func append(contentsOf newElements: Substring) Required

Declaration

public mutating func append(contentsOf newElements: Substring)
func append(contentsOf newElements: S) Required

Appends the characters in the given sequence to the string.

  • Parameter newElements: A sequence of characters.

Declaration

public mutating func append<S>(contentsOf newElements: S) where S: Sequence, S.Element == Character
func applying(_ difference: CollectionDifference<Self.Element>) -> Self? Required

Applies the given difference to this collection.

  • Parameter difference: The difference to be applied.

Complexity: O(n + c), where n is self.count and c is the number of changes contained by the parameter.

Declaration

@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func applying(_ difference: CollectionDifference<Self.Element>) -> Self?
func difference(from other: C, by areEquivalent: (C.Element, Self.Element) -> Bool) -> CollectionDifference<Self.Element> Required

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

This function does not infer element moves. If you need to infer moves, call the inferringMoves() method on the resulting difference.

Complexity: Worst case performance is O(n * m), where n is the count of this collection and m is other.count. You can expect faster execution when the collections share many common elements.

Declaration

@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func difference<C>(from other: C, by areEquivalent: (C.Element, Self.Element) -> Bool) -> CollectionDifference<Self.Element> where C: BidirectionalCollection, Self.Element == C.Element
func distance(from start: Self.Index, to end: Self.Index) -> Int Required

Declaration

@inlinable public func distance(from start: Self.Index, to end: Self.Index) -> Int
func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance Required

Returns the distance between two indices.

Complexity: O(n), where n is the resulting distance.

Declaration

@inlinable public func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance
func dropLast(_ k: Int) -> Self.SubSequence Required

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

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter k: The number of elements to drop off the end of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop.

Declaration

@inlinable public func dropLast(_ k: Int) -> Self.SubSequence
func encode(to encoder: Encoder) throws Required

Encodes this value into the given encoder.

This function throws an error if any values are invalid for the given encoder's format.

  • Parameter encoder: The encoder to write data to.

Declaration

public func encode(to encoder: Encoder) throws
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> Self Required

Returns a new collection of the same type containing, in order, the elements of the original collection that satisfy the given predicate.

In this example, filter(_:) is used to include only names shorter than five characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"
  • Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned collection.

Complexity: O(n), where n is the length of the collection.

Declaration

@available(swift 4.0) @inlinable public func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> Self
func formIndex(before i: inout Self.Index) Required

Replaces the given index with its predecessor.

  • Parameter i: A valid index of the collection. i must be greater than startIndex.

Declaration

@inlinable public func formIndex(before i: inout Self.Index)
func hasPrefix(_ prefix: String) -> Bool Required

Declaration

public func hasPrefix(_ prefix: String) -> Bool
func hasSuffix(_ suffix: String) -> Bool Required

Declaration

public func hasSuffix(_ suffix: String) -> Bool
func hash(into hasher: inout Hasher) Required

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

  • Parameter hasher: The hasher to use when combining the components of this instance.

Declaration

public func hash(into hasher: inout Hasher)
func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index Required

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index
func index(_ i: String.Index, offsetBy n: String.IndexDistance) -> String.Index Required

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

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as n must not offset i beyond the bounds of the collection.

Complexity: O(n), where n is the absolute value of n.

Declaration

@inlinable public func index(_ i: String.Index, offsetBy n: String.IndexDistance) -> String.Index
func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index? Required

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
func index(_ i: String.Index, offsetBy n: String.IndexDistance, limitedBy limit: String.Index) -> String.Index? Required

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

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as n must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(n), where n is the absolute value of n.

Declaration

@inlinable public func index(_ i: String.Index, offsetBy n: String.IndexDistance, limitedBy limit: String.Index) -> String.Index?
func index(after i: String.Index) -> String.Index Required

Returns the position immediately after the given index.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

public func index(after i: String.Index) -> String.Index
func index(before i: String.Index) -> String.Index Required

Returns the position immediately before the given index.

  • Parameter i: A valid index of the collection. i must be greater than startIndex.

Declaration

public func index(before i: String.Index) -> String.Index
func insert(_ newElement: Self.Element, at i: Self.Index) Required

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

The new element is inserted before the element currently at the specified index. If you pass the collection's endIndex property as the index parameter, the new element is appended to the collection.

var numbers = [1, 2, 3, 4, 5]
numbers.insert(100, at: 3)
numbers.insert(200, at: numbers.endIndex)

print(numbers)
// Prints "[1, 2, 3, 100, 4, 5, 200]"

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter newElement: The new element to insert into the collection.
  • Parameter i: The position at which to insert the new element. index must be a valid index into the collection.

Complexity: O(n), where n is the length of the collection. If i == endIndex, this method is equivalent to append(_:).

Declaration

@inlinable public mutating func insert(_ newElement: Self.Element, at i: Self.Index)
func insert(_ newElement: Character, at i: String.Index) Required

Inserts a new character at the specified position.

Calling this method invalidates any existing indices for use with this string.

Complexity: O(n), where n is the length of the string.

Declaration

public mutating func insert(_ newElement: Character, at i: String.Index)
func insert(contentsOf newElements: C, at i: Self.Index) Required

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

The new elements are inserted before the element currently at the specified index. If you pass the collection's endIndex property as the index parameter, the new elements are appended to the collection.

Here's an example of inserting a range of integers into an array of the same type:

var numbers = [1, 2, 3, 4, 5]
numbers.insert(contentsOf: 100...103, at: 3)
print(numbers)
// Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter newElements: The new elements to insert into the collection.
  • Parameter i: The position at which to insert the new elements. index must be a valid index of the collection.

Complexity: O(n + m), where n is length of this collection and m is the length of newElements. If i == endIndex, this method is equivalent to append(contentsOf:).

Declaration

@inlinable public mutating func insert<C>(contentsOf newElements: C, at i: Self.Index) where C: Collection, Self.Element == C.Element
func insert(contentsOf newElements: S, at i: String.Index) Required

Inserts a collection of characters at the specified position.

Calling this method invalidates any existing indices for use with this string.

Complexity: O(n), where n is the combined length of the string and newElements.

Declaration

public mutating func insert<S>(contentsOf newElements: S, at i: String.Index) where S: Collection, S.Element == Character
func last(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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

This example uses the last(where:) method to find the last negative number in an array of integers:

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let lastNegative = numbers.last(where: { $0 < 0 }) {
    print("The last negative number is \(lastNegative).")
}
// Prints "The last negative number is -6."
  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func last(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?
func lastIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index? Required

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

You can use the predicate to find an element of a type that doesn't conform to the Equatable protocol or to find an element that matches particular criteria. This example finds the index of the last name that begins with the letter A:

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Akosua starts with 'A'!"
  • Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func lastIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
func lowercased() -> String Required

Returns a lowercase version of the string.

Here's an example of transforming a string to all lowercase letters.

let cafe = "BBQ Café 🍵"
print(cafe.lowercased())
// Prints "bbq café 🍵"

Complexity: O(n)

Declaration

public func lowercased() -> String
func makeContiguousUTF8() Required

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

Complexity: O(n) if non-contiguous, O(1) if already contiguous

Declaration

public mutating func makeContiguousUTF8()
func makeIterator() -> String.Iterator Required

Returns an iterator over the elements of the collection.

Declaration

@inlinable public func makeIterator() -> String.Iterator
func max(_ x: T, _ y: T) -> T Required

Declaration

public func max<T>(_ x: T, _ y: T) -> T where T: Comparable
func min(_ x: T, _ y: T) -> T Required

Declaration

public func min<T>(_ x: T, _ y: T) -> T where T: Comparable
func next() -> Character? Required

Advances to the next element and returns it, or nil if no next element exists.

Repeatedly calling this method returns, in order, all the elements of the underlying sequence. As soon as the sequence has run out of elements, all subsequent calls return nil.

You must not call this method if any other copy of this iterator has been advanced with a call to its next() method.

The following example shows how an iterator can be used explicitly to emulate a for-in loop. First, retrieve a sequence's iterator, and then call the iterator's next() method until it returns nil.

let numbers = [2, 3, 5, 7]
var numbersIterator = numbers.makeIterator()

while let num = numbersIterator.next() {
    print(num)
}
// Prints "2"
// Prints "3"
// Prints "5"
// Prints "7"

Declaration

@inlinable public mutating func next() -> Character?
func remove(at position: Self.Index) -> Self.Element Required

Removes and returns the element at the specified position.

All the elements following the specified position are moved to close the gap. This example removes the middle element from an array of measurements.

var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
let removed = measurements.remove(at: 2)
print(measurements)
// Prints "[1.2, 1.5, 1.2, 1.6]"

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter position: The position of the element to remove. position must be a valid index of the collection that is not equal to the collection's end index.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func remove(at position: Self.Index) -> Self.Element
func remove(at i: String.Index) -> Character Required

Removes and returns the character at the specified position.

All the elements following i are moved to close the gap. This example removes the hyphen from the middle of a string.

var nonempty = "non-empty"
if let i = nonempty.firstIndex(of: "-") {
    nonempty.remove(at: i)
}
print(nonempty)
// Prints "nonempty"

Calling this method invalidates any existing indices for use with this string.

  • Parameter i: The position of the character to remove. i must be a valid index of the string that is not equal to the string's end index.

Declaration

public mutating func remove(at i: String.Index) -> Character
func removeAll(keepingCapacity keepCapacity: Bool = false) Required

Removes all elements from the collection.

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter keepCapacity: Pass true to request that the collection avoid releasing its storage. Retaining the collection's storage can be a useful optimization when you're planning to grow the collection again. The default value is false.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false)
func removeAll(keepingCapacity keepCapacity: Bool = false) Required

Replaces this string with the empty string.

Calling this method invalidates any existing indices for use with this string.

  • Parameter keepCapacity: Pass true to prevent the release of the string's allocated storage. Retaining the storage can be a useful optimization when you're planning to grow the string again. The default value is false.

Declaration

public mutating func removeAll(keepingCapacity keepCapacity: Bool = false)
func removeAll(where shouldBeRemoved: (Self.Element) throws -> Bool) rethrows Required

Removes all the elements that satisfy the given predicate.

Use this method to remove every element in a collection that meets particular criteria. The order of the remaining elements is preserved. This example removes all the vowels from a string:

var phrase = "The rain in Spain stays mainly in the plain."

let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."
  • Parameter shouldBeRemoved: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be removed from the collection.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func removeAll(where shouldBeRemoved: (Self.Element) throws -> Bool) rethrows
func removeFirst() -> Self.Element Required

Removes and returns the first element of the collection.

The collection must not be empty.

var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst()
print(bugs)
// Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"

Calling this method may invalidate any existing indices for use with this collection.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func removeFirst() -> Self.Element
func removeFirst(_ k: Int) Required

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

var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst(3)
print(bugs)
// Prints "["Damselfly", "Earwig"]"

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter k: The number of elements to remove from the collection. k must be greater than or equal to zero and must not exceed the number of elements in the collection.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func removeFirst(_ k: Int)
func removeSubrange(_ bounds: Range<Self.Index>) Required

Removes the elements in the specified subrange from the collection.

All the elements following the specified position are moved to close the gap. This example removes three elements from the middle of an array of measurements.

var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
measurements.removeSubrange(1..<4)
print(measurements)
// Prints "[1.2, 1.5]"

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter bounds: The range of the collection to be removed. The bounds of the range must be valid indices of the collection.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func removeSubrange(_ bounds: Range<Self.Index>)
func removeSubrange(_ bounds: R) Required

Removes the elements in the specified subrange from the collection.

All the elements following the specified position are moved to close the gap. This example removes three elements from the middle of an array of measurements.

var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
measurements.removeSubrange(1..<4)
print(measurements)
// Prints "[1.2, 1.5]"

Calling this method may invalidate any existing indices for use with this collection.

  • Parameter bounds: The range of the collection to be removed. The bounds of the range must be valid indices of the collection.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public mutating func removeSubrange<R>(_ bounds: R) where R: RangeExpression, Self.Index == R.Bound
func removeSubrange(_ bounds: Range<String.Index>) Required

Removes the characters in the given range.

Calling this method invalidates any existing indices for use with this string.

  • Parameter bounds: The range of the elements to remove. The upper and lower bounds of bounds must be valid indices of the string and not equal to the string's end index.
  • Parameter bounds: The range of the elements to remove. The upper and lower bounds of bounds must be valid indices of the string.

Declaration

public mutating func removeSubrange(_ bounds: Range<String.Index>)
func replaceSubrange(_ subrange: R, with newElements: C) Required

Replaces the specified subrange of elements with the given collection.

This method has the effect of removing the specified range of elements from the collection and inserting the new elements at the same location. The number of new elements need not match the number of elements being removed.

In this example, three elements in the middle of an array of integers are replaced by the five elements of a Repeated<Int> instance.

 var nums = [10, 20, 30, 40, 50]
 nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
 print(nums)
 // Prints "[10, 1, 1, 1, 1, 1, 50]"

If you pass a zero-length range as the subrange parameter, this method inserts the elements of newElements at subrange.startIndex. Calling the insert(contentsOf:at:) method instead is preferred.

Likewise, if you pass a zero-length collection as the newElements parameter, this method removes the elements in the given subrange without replacement. Calling the removeSubrange(_:) method instead is preferred.

Calling this method may invalidate any existing indices for use with this collection.

Complexity: O(n + m), where n is length of this collection and m is the length of newElements. If the call to this method simply appends the contents of newElements to the collection, the complexity is O(m).

Declaration

@inlinable public mutating func replaceSubrange<C, R>(_ subrange: R, with newElements: C) where C: Collection, R: RangeExpression, Self.Element == C.Element, Self.Index == R.Bound
func replaceSubrange(_ bounds: Range<String.Index>, with newElements: C) Required

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

Calling this method invalidates any existing indices for use with this string.

Complexity: O(m), where m is the combined length of the string and newElements. If the call to replaceSubrange(_:with:) simply removes text at the end of the string, the complexity is O(n), where n is equal to bounds.count.

Declaration

public mutating func replaceSubrange<C>(_ bounds: Range<String.Index>, with newElements: C) where C: Collection, C.Element == Character
func reserveCapacity(_ n: Int) Required

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

If you will be adding a known number of elements to a collection, use this method to avoid multiple reallocations. A type that conforms to RangeReplaceableCollection can choose how to respond when this method is called. Depending on the type, it may make sense to allocate more or less storage than requested or to take no action at all.

  • Parameter n: The requested number of elements to store.

Declaration

@inlinable public mutating func reserveCapacity(_ n: Int)
func reserveCapacity(_ n: Int) Required

Reserves enough space in the string's underlying storage to store the specified number of ASCII characters.

Because each character in a string can require more than a single ASCII character's worth of storage, additional allocation may be necessary when adding characters to a string after a call to reserveCapacity(_:).

  • Parameter n: The minimum number of ASCII character's worth of storage to allocate.

Complexity: O(n)

Declaration

public mutating func reserveCapacity(_ n: Int)
func reversed() -> ReversedCollection<Self> Required

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

You can reverse a collection without allocating new space for its elements by calling this reversed() method. A ReversedCollection instance wraps an underlying collection and provides access to its elements in reverse order. This example prints the characters of a string in reverse order:

let word = "Backwards"
for char in word.reversed() {
    print(char, terminator: "")
}
// Prints "sdrawkcaB"

If you need a reversed collection of the same type, you may be able to use the collection's sequence-based or collection-based initializer. For example, to get the reversed version of a string, reverse its characters and initialize a new String instance from the result.

let reversedWord = String(word.reversed())
print(reversedWord)
// Prints "sdrawkcaB"

Complexity: O(1)

Declaration

@inlinable public func reversed() -> ReversedCollection<Self>
func suffix(_ maxLength: Int) -> Self.SubSequence Required

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

If the maximum length exceeds the number of elements in the collection, the result contains the entire collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is equal to maxLength.

Declaration

@inlinable public func suffix(_ maxLength: Int) -> Self.SubSequence
func uppercased() -> String Required

Returns an uppercase version of the string.

The following example transforms a string to uppercase letters:

let cafe = "Café 🍵"
print(cafe.uppercased())
// Prints "CAFÉ 🍵"

Complexity: O(n)

Declaration

public func uppercased() -> String
func withCString(_ body: (UnsafePointer<Int8>) throws -> Result) rethrows -> Result Required

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

The pointer passed as an argument to body is valid only during the execution of withCString(_:). Do not store or return the pointer for later use.

  • Parameter body: A closure with a pointer parameter that points to a null-terminated sequence of UTF-8 code units. If body has a return value, that value is also used as the return value for the withCString(_:) method. The pointer argument is valid only for the duration of the method's execution.

Declaration

@inlinable public func withCString<Result>(_ body: (UnsafePointer<Int8>) throws -> Result) rethrows -> Result
func withCString(encodedAs targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result) rethrows -> Result Required

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

The pointer passed as an argument to body is valid only during the execution of withCString(encodedAs:_:). Do not store or return the pointer for later use.

Declaration

@inlinable public func withCString<Result, TargetEncoding>(encodedAs targetEncoding: TargetEncoding.Type, _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result) rethrows -> Result where TargetEncoding: _UnicodeEncoding
func withUTF8(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R Required

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

Note that it is unsafe to escape the pointer provided to body. For example, strings of up to 15 UTF-8 code units in length may be represented in a small-string representation, and thus will be spilled into temporary stack space which is invalid after withUTF8 finishes execution.

Complexity: O(n) if non-contiguous, O(1) if already contiguous

Declaration

public mutating func withUTF8<R>(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R
func write(_ other: String) Required

Appends the given string to this string.

  • Parameter other: A string to append.

Declaration

public mutating func write(_ other: String)
func write(to target: inout Target) Required

Writes the string into the given output stream.

  • Parameter target: An output stream.

Declaration

public func write<Target>(to target: inout Target) where Target: TextOutputStream

Type Methods

func !=(lhs: Self, rhs: Self) -> Bool Required

Declaration

public static func !=(lhs: Self, rhs: Self) -> Bool
func +(lhs: Self, rhs: Other) -> Self Required

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

The two arguments must have the same Element type. For example, you can concatenate the elements of an integer array and a Range<Int> instance.

let numbers = [1, 2, 3, 4]
let moreNumbers = numbers + 5...10
print(moreNumbers)
// Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"

The resulting collection has the type of the argument on the left-hand side. In the example above, moreNumbers has the same type as numbers, which is [Int].

Declaration

@inlinable public static func +<Other>(lhs: Self, rhs: Other) -> Self where Other: Sequence, Self.Element == Other.Element
func +(lhs: Other, rhs: Self) -> Self Required

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

The two arguments must have the same Element type. For example, you can concatenate the elements of a Range<Int> instance and an integer array.

let numbers = [7, 8, 9, 10]
let moreNumbers = 1...6 + numbers
print(moreNumbers)
// Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"

The resulting collection has the type of argument on the right-hand side. In the example above, moreNumbers has the same type as numbers, which is [Int].

Declaration

@inlinable public static func +<Other>(lhs: Other, rhs: Self) -> Self where Other: Sequence, Self.Element == Other.Element
func +(lhs: Self, rhs: Other) -> Self Required

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

The two arguments must have the same Element type. For example, you can concatenate the elements of two integer arrays.

let lowerNumbers = [1, 2, 3, 4]
let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10]
let allNumbers = lowerNumbers + higherNumbers
print(allNumbers)
// Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"

The resulting collection has the type of the argument on the left-hand side. In the example above, moreNumbers has the same type as numbers, which is [Int].

Declaration

@inlinable public static func +<Other>(lhs: Self, rhs: Other) -> Self where Other: RangeReplaceableCollection, Self.Element == Other.Element
func +(lhs: String, rhs: String) -> String Required

Declaration

@inlinable public static func +(lhs: String, rhs: String) -> String
func +=(lhs: inout Self, rhs: Other) Required

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

Use this operator to append the elements of a sequence to the end of range-replaceable collection with same Element type. This example appends the elements of a Range<Int> instance to an array of integers.

var numbers = [1, 2, 3, 4, 5]
numbers += 10...15
print(numbers)
// Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"

Complexity: O(m), where m is the length of the right-hand-side argument.

Declaration

@inlinable public static func +=<Other>(lhs: inout Self, rhs: Other) where Other: Sequence, Self.Element == Other.Element
func +=(lhs: inout String, rhs: String) Required

Declaration

@inlinable public static func +=(lhs: inout String, rhs: String)
func ...(maximum: Self) -> PartialRangeThrough<Self> Required

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

Use the prefix closed range operator (prefix ...) to create a partial range of any type that conforms to the Comparable protocol. This example creates a PartialRangeThrough<Double> instance that includes any value less than or equal to 5.0.

let throughFive = ...5.0

throughFive.contains(4.0)     // true
throughFive.contains(5.0)     // true
throughFive.contains(6.0)     // false

You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, and including, the partial range's upper bound.

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[...3])
// Prints "[10, 20, 30, 40]"
  • Parameter maximum: The upper bound for the range.

Declaration

prefix public static func ...(maximum: Self) -> PartialRangeThrough<Self>
func ...(minimum: Self) -> PartialRangeFrom<Self> Required

Returns a partial range extending upward from a lower bound.

Use the postfix range operator (postfix ...) to create a partial range of any type that conforms to the Comparable protocol. This example creates a PartialRangeFrom<Double> instance that includes any value greater than or equal to 5.0.

let atLeastFive = 5.0...

atLeastFive.contains(4.0)     // false
atLeastFive.contains(5.0)     // true
atLeastFive.contains(6.0)     // true

You can use this type of partial range of a collection's indices to represent the range from the partial range's lower bound up to the end of the collection.

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[3...])
// Prints "[40, 50, 60, 70]"
  • Parameter minimum: The lower bound for the range.

Declaration

postfix public static func ...(minimum: Self) -> PartialRangeFrom<Self>
func ...(minimum: Self, maximum: Self) -> ClosedRange<Self> Required

Returns a closed range that contains both of its bounds.

Use the closed range operator (...) to create a closed range of any type that conforms to the Comparable protocol. This example creates a ClosedRange<Character> from "a" up to, and including, "z".

let lowercase = "a"..."z"
print(lowercase.contains("z"))
// Prints "true"

Declaration

public static func ...(minimum: Self, maximum: Self) -> ClosedRange<Self>
func ..<(maximum: Self) -> PartialRangeUpTo<Self> Required

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

Use the prefix half-open range operator (prefix ..<) to create a partial range of any type that conforms to the Comparable protocol. This example creates a PartialRangeUpTo<Double> instance that includes any value less than 5.0.

let upToFive = ..<5.0

upToFive.contains(3.14)       // true
upToFive.contains(6.28)       // false
upToFive.contains(5.0)        // false

You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, but not including, the partial range's upper bound.

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[..<3])
// Prints "[10, 20, 30]"
  • Parameter maximum: The upper bound for the range.

Declaration

prefix public static func ..<(maximum: Self) -> PartialRangeUpTo<Self>
func ..<(minimum: Self, maximum: Self) -> Range<Self> Required

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

Use the half-open range operator (..<) to create a range of any type that conforms to the Comparable protocol. This example creates a Range<Double> from zero up to, but not including, 5.0.

let lessThanFive = 0.0..<5.0
print(lessThanFive.contains(3.14))  // Prints "true"
print(lessThanFive.contains(5.0))   // Prints "false"

Declaration

public static func ..<(minimum: Self, maximum: Self) -> Range<Self>
func <(lhs: String, rhs: String) -> Bool Required

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

This function is the only requirement of the Comparable protocol. The remainder of the relational operator functions are implemented by the standard library for any type that conforms to Comparable.

Declaration

@inlinable public static func <(lhs: String, rhs: String) -> Bool
func <=(lhs: Self, rhs: Self) -> Bool Required

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

This is the default implementation of the less-than-or-equal-to operator (<=) for any type that conforms to Comparable.

Declaration

@inlinable public static func <=(lhs: Self, rhs: Self) -> Bool
func ==(lhs: String, rhs: String) -> Bool Required

Returns a Boolean value indicating whether two values are equal.

Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.

Declaration

@inlinable public static func ==(lhs: String, rhs: String) -> Bool
func >(lhs: Self, rhs: Self) -> Bool Required

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

This is the default implementation of the greater-than operator (>) for any type that conforms to Comparable.

Declaration

@inlinable public static func >(lhs: Self, rhs: Self) -> Bool
func >=(lhs: Self, rhs: Self) -> Bool Required

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

This is the default implementation of the greater-than-or-equal-to operator (>=) for any type that conforms to Comparable.

Declaration

@inlinable public static func >=(lhs: Self, rhs: Self) -> Bool
func decodeCString(_ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? Required

Creates a new string by copying the null-terminated data referenced by the given pointer using the specified encoding.

When you pass true as isRepairing, this method replaces ill-formed sequences with the Unicode replacement character ("\u{FFFD}"); otherwise, an ill-formed sequence causes this method to stop decoding and return nil.

The following example calls this method with pointers to the contents of two different CChar arrays---the first with well-formed UTF-8 code unit sequences and the second with an ill-formed sequence at the end.

let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0]
validUTF8.withUnsafeBufferPointer { ptr in
    let s = String.decodeCString(ptr.baseAddress,
                                 as: UTF8.self,
                                 repairingInvalidCodeUnits: true)
    print(s)
}
// Prints "Optional((Café, false))"

let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0]
invalidUTF8.withUnsafeBufferPointer { ptr in
    let s = String.decodeCString(ptr.baseAddress,
                                 as: UTF8.self,
                                 repairingInvalidCodeUnits: true)
    print(s)
}
// Prints "Optional((Caf�, true))"

Declaration

@inlinable public static func decodeCString<Encoding>(_ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) -> (result: String, repairsMade: Bool)? where Encoding: _UnicodeEncoding