String

struct String

A Unicode string value.

A string is a series of characters, such as "Swift". Strings in Swift are Unicode correct, locale insensitive, and 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 are 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)!"

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

Combine strings using the concatenation operator (+).

let longerGreeting = greeting + " We're glad you're here!"
print(longerGreeting)
// Prints "Welcome! We're glad you're here!"

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!"
print(otherGreeting)
// Prints "Welcome! Have a nice time!"

print(greeting)
// Prints "Welcome!"

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

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

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

Basic string operations are not sensitive to locale settings. This ensures 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.

Representing Strings: Views

A string is not itself a collection. Instead, it has properties that present its contents as meaningful collections. Each of these collections is a particular type of view of the string's visible and data representation.

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 🌍"

Character View

A string's characters property 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 code points. These code points are combined by Unicode's boundary algorithms into extended grapheme clusters, represented by Swift's Character type. Each element of the characters view is represented by a Character instance.

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

Each visible character in the cafe string is a separate element of the characters view.

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 UnicodeScalar 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 code points 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.

The elements of this collection 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"

Counting 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.characters.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 scalars 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.characters.count)
// Prints "1"
print(flag.unicodeScalars.count)
// Prints "2"
print(flag.utf16.count)
// Prints "4"
print(flag.utf8.count)
// Prints "8"

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 characters view for a space and then create a new string from a prefix of the characters view up to that point.

let name = "Marie Curie"
let firstSpace = name.characters.index(of: " ")!
let firstName = String(name.characters.prefix(upTo: firstSpace))
print(firstName)
// Prints "Marie"

You can convert an index into one of a string's views to an index into another view.

let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8)
print(Array(name.utf8.prefix(upTo: firstSpaceUTF8)))
// Prints "[77, 97, 114, 105, 101]"

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.

See Also: String.CharacterView, String.UnicodeScalarView, String.UTF16View, String.UTF8View

Inheritance Comparable, CustomDebugStringConvertible, CustomPlaygroundQuickLookable, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByStringInterpolation, ExpressibleByStringLiteral, ExpressibleByUnicodeScalarLiteral, Hashable, LosslessStringConvertible, MirrorPath, TextOutputStream, TextOutputStreamable View Protocol Hierarchy →
Associated Types
UTF16Index = String.UTF16View.Index

The index type for subscripting a string's utf16 view.

UTF8Index = String.UTF8View.Index

The index type for subscripting a string's utf8 view.

Index = String.CharacterView.Index

The index type for subscripting a string.

IndexDistance = String.CharacterView.IndexDistance

A type used to represent the number of steps between two String.Index values, where one value is reachable from the other.

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

UnicodeScalarIndex = String.UnicodeScalarView.Index

The index type for a string's unicodeScalars view.

Nested Types String.UTF16View, String.UTF8View, String.CharacterView, String.UnicodeScalarView, String.UTF16View.Index, String.UTF16View.Indices, String.UTF8View.Index, String.CharacterView.Index, String.UnicodeScalarView.Index, String.UnicodeScalarView.Iterator
Import import Swift

Initializers

init()

Creates an empty string.

Declaration

init()
init(_: Character)

Creates a string containing the given character.

c: The character to convert to a string.

Declaration

init(_ c: Character)
init(_: NSString)

[Foundation]

Declaration

init(_ cocoaString: NSString)
init(_: String.CharacterView)

Creates a string from the given character view.

Use this initializer to recover a string after performing a collection slicing operation on a character view.

let poem = "'Twas brillig, and the slithy toves / " +
           "Did gyre and gimbal in the wabe: / " +
           "All mimsy were the borogoves / " +
           "And the mome raths outgrabe."
let excerpt = String(poem.characters.prefix(22)) + "..."
print(excerpt)
// Prints "'Twas brillig, and the..."

characters: A character view to convert to a string.

Declaration

init(_ characters: String.CharacterView)
init(_: String.UnicodeScalarView)

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.index(of: " ") {
    let adjective = String(picnicGuest.unicodeScalars.prefix(upTo: i))
    print(adjective)
}
// Prints "Deserving"

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

unicodeScalars: A collection of Unicode scalar values.

Declaration

init(_ unicodeScalars: String.UnicodeScalarView)
init<T : _SignedInteger>(_: T)

Creates a string representing the given value in base 10.

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

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

Declaration

init<T : _SignedInteger>(_ v: T)
init<T : UnsignedInteger>(_: T)

Creates a string representing the given value in base 10.

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

let max = String(UInt.max)
print("\(max) has \(max.utf16.count) digits.")
// Prints "18446744073709551615 has 20 digits."

Declaration

init<T : UnsignedInteger>(_ v: T)
init<T : LosslessStringConvertible>(_: T)

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

Declaration

init<T : LosslessStringConvertible>(_ value: T)
init<S : Sequence where S.Iterator.Element == Character>(_: S)

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 operations on a string's characters view. 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.characters.lazy.filter { !vowels.contains($0) })

print(disemvoweled)
// Prints "Th rn n Spn stys mnly n th pln."

characters: A sequence of characters.

Declaration

init<S : Sequence where S.Iterator.Element == Character>(_ characters: S)
init<T : _SignedInteger>(_: T, radix: Int, uppercase: Bool)

Creates a string representing the given value in the specified base.

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"

Parameters: value: The value to convert to a string. radix: The base to use for the string representation. radix must be at least 2 and at most 36. uppercase: Pass true to use uppercase letters to represent numerals greater than 9, or false to use lowercase letters. The default is false.

Declaration

init<T : _SignedInteger>(_ value: T, radix: Int, uppercase: Bool = default)
init<T : UnsignedInteger>(_: T, radix: Int, uppercase: Bool)

Creates a string representing the given value in the specified base.

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

let v: UInt = 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"

Parameters: value: The value to convert to a string. radix: The base to use for the string representation. radix must be at least 2 and at most 36. uppercase: Pass true to use uppercase letters to represent numerals greater than 9, or false to use lowercase letters. The default is false.

Declaration

init<T : UnsignedInteger>(_ value: T, radix: Int, uppercase: Bool = default)
init(cString: UnsafePointer<CChar>)

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�"

cString: A pointer to a null-terminated UTF-8 code sequence.

Declaration

init(cString: UnsafePointer<CChar>)
init(cString: UnsafePointer<UInt8>)

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

init(cString: UnsafePointer<UInt8>)
init(contentsOf:)

[Foundation]

Declaration

init(contentsOf url: URL)
init(contentsOf:encoding:)

[Foundation] Produces a string created by reading data from a given URL interpreted using a given encoding. Errors are written into the inout error argument.

Declaration

init(contentsOf url: URL, encoding enc: String.Encoding)
init(contentsOf:usedEncoding:)

[Foundation] Produces a string created by reading data from a given URL and returns by reference the encoding used to interpret the data. Errors are written into the inout error argument.

Declaration

init(contentsOf url: URL, usedEncoding: inout String.Encoding)
init(contentsOfFile:)

[Foundation]

Declaration

init(contentsOfFile path: String)
init(contentsOfFile:encoding:)

[Foundation] Produces a string created by reading data from the file at a given path interpreted using a given encoding.

Declaration

init(contentsOfFile path: String, encoding enc: String.Encoding)
init(contentsOfFile:usedEncoding:)

[Foundation] Produces a string created by reading data from the file at a given path and returns by reference the encoding used to interpret the file.

Declaration

init(contentsOfFile path: String, usedEncoding: inout String.Encoding)
init(describing:)

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:

  • If instance conforms to the TextOutputStreamable protocol, the result is obtained by calling instance.write(to: s) on an empty string s.
  • If instance conforms to the CustomStringConvertible protocol, the result is instance.description.
  • If instance conforms to the CustomDebugStringConvertible protocol, the result is instance.debugDescription.
  • An unspecified result is supplied automatically by the Swift standard library.

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)"

See Also: String.init<Subject>(reflecting: Subject)

Declaration

init<Subject>(describing instance: Subject)
init(extendedGraphemeClusterLiteral:)

Creates an instance initialized to the given extended grapheme cluster literal.

Don't call this initializer directly. It may be used by the compiler when you initialize a string using a string literal containing a single extended grapheme cluster.

Declaration

init(extendedGraphemeClusterLiteral value: String)
init(format:_:)

[Foundation] Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted.

Declaration

init(format: String, _ arguments: CVarArg...)
init(format:arguments:)

[Foundation] Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to the user's default locale.

Declaration

init(format: String, arguments: [CVarArg])
init(format:locale:_:)

[Foundation] Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale information.

Declaration

init(format: String, locale: Locale?, _ args: CVarArg...)
init(format:locale:arguments:)

[Foundation] Returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted according to given locale information.

Declaration

init(format: String, locale: Locale?, arguments: [CVarArg])
init(reflecting:)

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:

  • If subject conforms to the CustomDebugStringConvertible protocol, the result is subject.debugDescription.
  • If subject conforms to the CustomStringConvertible protocol, the result is subject.description.
  • If subject conforms to the TextOutputStreamable protocol, the result is obtained by calling subject.write(to: s) on an empty string s.
  • An unspecified result is supplied automatically by the Swift standard library.

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)"

See Also: String.init<Subject>(Subject)

Declaration

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

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

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

let zeroes = String(repeating: "00", count: 10)
print(zeroes)
// Prints "00000000000000000000"

Parameters: repeatedValue: The string to repeat. count: The number of times to repeat repeatedValue in the resulting string.

Declaration

init(repeating repeatedValue: String, count: Int)
init(stringInterpolation:)

Creates a new string by concatenating the given interpolations.

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

init(stringInterpolation strings: String...)
init(stringInterpolationSegment: Bool)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Bool)
init(stringInterpolationSegment: Character)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Character)
init(stringInterpolationSegment: Float32)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Float32)
init(stringInterpolationSegment: Float64)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Float64)
init(stringInterpolationSegment: Int)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Int)
init(stringInterpolationSegment: Int8)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Int8)
init(stringInterpolationSegment: Int16)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Int16)
init(stringInterpolationSegment: Int32)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Int32)
init(stringInterpolationSegment: Int64)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: Int64)
init(stringInterpolationSegment: String)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: String)
init(stringInterpolationSegment: UInt)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: UInt)
init(stringInterpolationSegment: UInt8)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: UInt8)
init(stringInterpolationSegment: UInt16)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: UInt16)
init(stringInterpolationSegment: UInt32)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: UInt32)
init(stringInterpolationSegment: UInt64)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: UInt64)
init(stringInterpolationSegment: UnicodeScalar)

Creates a string containing the given value's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init(stringInterpolationSegment expr: UnicodeScalar)
init<T>(stringInterpolationSegment: T)

Creates a string containing the given expression's textual representation.

Do not call this initializer directly. It is used by the compiler when interpreting string interpolations.

See Also: ExpressibleByStringInterpolation

Declaration

init<T>(stringInterpolationSegment expr: T)
init(stringLiteral:)

Creates an instance initialized to the given string value.

Don't 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

init(stringLiteral value: String)
init(unicodeScalarLiteral:)

Creates an instance initialized to the given Unicode scalar value.

Don't call this initializer directly. It may be used by the compiler when you initialize a string using a string literal that contains a single Unicode scalar value.

Declaration

init(unicodeScalarLiteral value: String)
init(utf16CodeUnits:count:)

[Foundation] Returns an initialized String object that contains a given number of characters from a given array of Unicode characters.

Declaration

init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)
init(utf16CodeUnitsNoCopy:count:freeWhenDone:)

[Foundation] Returns an initialized String object that contains a given number of characters from a given array of UTF-16 Code Units

Declaration

init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool)
init?(_: String)

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

Declaration

init?(_ description: String)
init?(_: String.UTF8View)

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

If utf8 is an ill-formed UTF-8 code sequence, the result is nil.

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

let picnicGuest = "Deserving porcupine"
if let i = picnicGuest.utf8.index(of: 32) {
    let adjective = String(picnicGuest.utf8.prefix(upTo: i))
    print(adjective)
}
// Prints "Optional(Deserving)"

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

utf8: A UTF-8 code sequence.

Declaration

init?(_ utf8: String.UTF8View)
init?(_: String.UTF16View)

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

If utf16 contains unpaired UTF-16 surrogates, the result is nil.

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

let picnicGuest = "Deserving porcupine"
if let i = picnicGuest.utf16.index(of: 32) {
    let adjective = String(picnicGuest.utf16.prefix(upTo: i))
    print(adjective)
}
// Prints "Optional(Deserving)"

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

utf16: A UTF-16 code sequence.

Declaration

init?(_ utf16: String.UTF16View)
init?(bytes:encoding:)

[Foundation] Produces an initialized NSString object equivalent to the given bytes interpreted in the given encoding.

Declaration

init?<S : Sequence where S.Iterator.Element == UInt8>(bytes: S, encoding: String.Encoding)
init?(bytesNoCopy:length:encoding:freeWhenDone:)

[Foundation] Produces an initialized String object that contains a given number of bytes from a given buffer of bytes interpreted in a given encoding, and optionally frees the buffer. WARNING: this initializer is not memory-safe!

Declaration

init?(bytesNoCopy bytes: UnsafeMutablePointer<Swift.Void>, length: Int, encoding: String.Encoding, freeWhenDone flag: Bool)
init?(cString:encoding:)

[Foundation] Produces a string containing the bytes in a given C array, interpreted according to a given encoding.

Declaration

init?(cString: UnsafePointer<CChar>, encoding enc: String.Encoding)
init?(data:encoding:)

[Foundation] Returns a String initialized by converting given data into Unicode characters using a given encoding.

Declaration

init?(data: Data, encoding: String.Encoding)
init?(utf8String:)

[Foundation] Produces a string created by copying the data from a given C array of UTF8-encoded bytes.

Declaration

init?(utf8String bytes: UnsafePointer<CChar>)
init?(validatingUTF8:)

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"

cString: A pointer to a null-terminated UTF-8 code sequence.

Declaration

init?(validatingUTF8 cString: UnsafePointer<CChar>)

Instance Variables

var capitalized: String

[Foundation] Produce a string with the first character from each word changed to the corresponding uppercase value.

Declaration

var capitalized: String { get }
var characters: String.CharacterView

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

Declaration

var characters: String.CharacterView { get set }
var customMirror: Mirror

A mirror that reflects the String instance.

Declaration

var customMirror: Mirror { get }
var customPlaygroundQuickLook: PlaygroundQuickLook

A custom playground Quick Look for this instance.

If this type has value semantics, the PlaygroundQuickLook instance should be unaffected by subsequent mutations.

Declaration

var customPlaygroundQuickLook: PlaygroundQuickLook { get }
var debugDescription: String

A representation of the string that is suitable for debugging.

Declaration

var debugDescription: String { get }
var decomposedStringWithCanonicalMapping: String

[Foundation] Returns a string made by normalizing the String's contents using Form D.

Declaration

var decomposedStringWithCanonicalMapping: String { get }
var decomposedStringWithCompatibilityMapping: String

[Foundation] Returns a string made by normalizing the String's contents using Form KD.

Declaration

var decomposedStringWithCompatibilityMapping: String { get }
var description: String

A textual representation of this instance.

Instead of accessing this property directly, convert an instance of any type to a string by using the String(describing:) initializer. For example:

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

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

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

The conversion of p to a string in the assignment to s uses the Point type's description property.

Declaration

var description: String { get }
var endIndex: String.Index

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 { get }
var fastestEncoding: String.Encoding

[Foundation] Returns the fastest encoding to which the String may be converted without loss of information.

Declaration

var fastestEncoding: String.Encoding { get }
var hash: Int

[Foundation] An unsigned integer that can be used as a hash table address.

Declaration

var hash: Int { get }
var hashValue: Int

The string's hash value.

Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.

Declaration

var hashValue: Int { get }
var isEmpty: Bool

A Boolean value indicating whether a string has no characters.

Declaration

var isEmpty: Bool { get }
var localizedCapitalized: String

[Foundation] A capitalized representation of the String that is produced using the current locale.

Declaration

var localizedCapitalized: String { get }
var localizedLowercase: String

[Foundation] A lowercase version of the string that is produced using the current locale.

Declaration

var localizedLowercase: String { get }
var localizedUppercase: String

[Foundation] An uppercase version of the string that is produced using the current locale.

Declaration

var localizedUppercase: String { get }
var precomposedStringWithCanonicalMapping: String

[Foundation] Returns a string made by normalizing the String's contents using Form C.

Declaration

var precomposedStringWithCanonicalMapping: String { get }
var precomposedStringWithCompatibilityMapping: String

[Foundation] Returns a string made by normalizing the String's contents using Form KC.

Declaration

var precomposedStringWithCompatibilityMapping: String { get }
var removingPercentEncoding: String?

[Foundation] Returns a new string made from the String by replacing all percent encoded sequences with the matching UTF-8 characters.

Declaration

var removingPercentEncoding: String? { get }
var smallestEncoding: String.Encoding

[Foundation] Returns the smallest encoding to which the String can be converted without loss of information.

Declaration

var smallestEncoding: String.Encoding { get }
var startIndex: String.Index

The position of the first character in a nonempty string.

In an empty string, startIndex is equal to endIndex.

Declaration

var startIndex: String.Index { get }
var unicodeScalars: String.UnicodeScalarView

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

Declaration

var unicodeScalars: String.UnicodeScalarView { get set }
var utf8: String.UTF8View

A UTF-8 encoding of self.

Declaration

var utf8: String.UTF8View { get set }
var utf8CString: ContiguousArray<CChar>

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> { get }
var utf16: String.UTF16View

A UTF-16 encoding of self.

Declaration

var utf16: String.UTF16View { get set }

Subscripts

subscript(_: String.Index)

Accesses the character at the given position.

Indices for a subscripting a string are shared with the string's characters view. For example:

let greeting = "Hello, friend!"
if let i = greeting.characters.index(where: { $0 >= "A" && $0 <= "Z" }) {
    print("First capital letter: \(greeting[i])")
}
// Prints "First capital letter: H"

i: A valid index of the string. i must be less than the string's end index.

Declaration

subscript(i: String.Index) -> Character { get }
subscript(_: Range<String.Index>)

Accesses the text in the given range.

Complexity: O(n) if the underlying string is bridged from Objective-C, where n is the length of the string; otherwise, O(1).

Declaration

subscript(bounds: Range<String.Index>) -> String { get }
subscript(_: ClosedRange<String.Index>)

Accesses the text in the given range.

Complexity: O(n) if the underlying string is bridged from Objective-C, where n is the length of the string; otherwise, O(1).

Declaration

subscript(bounds: ClosedRange<String.Index>) -> String { get }

Static Methods

static func availableStringEncodings()

[Foundation] Returns an Array of the encodings string objects support in the application's environment.

Declaration

static func availableStringEncodings() -> [String.Encoding]
static func decodeCString(_:as:repairingInvalidCodeUnits:)

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))"

Parameters: cString: A pointer to a null-terminated code sequence encoded in encoding. encoding: The Unicode encoding of the data referenced by cString. isRepairing: Pass true to create a new string, even when the data referenced by cString contains ill-formed sequences. Ill-formed sequences are replaced with the Unicode replacement character ("\u{FFFD}"). Pass false to interrupt the creation of the new string if an ill-formed sequence is detected. Returns: A tuple with the new string and a Boolean value that indicates whether any repairs were made. If isRepairing is false and an ill-formed sequence is detected, this method returns nil.

See Also: UnicodeCodec

Declaration

static func decodeCString<Encoding : UnicodeCodec>(_ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = default) -> (result: String, repairsMade: Bool)?
static func defaultCStringEncoding()

[Foundation] Returns the C-string encoding assumed for any method accepting a C string as an argument.

Declaration

static func defaultCStringEncoding() -> String.Encoding
static func localizedName(of:)

[Foundation] Returns a human-readable string giving the name of a given encoding.

Declaration

static func localizedName(of encoding: String.Encoding) -> String
static func localizedStringWithFormat(_:_:)

[Foundation] Returns a string created by using a given format string as a template into which the remaining argument values are substituted according to the user's default locale.

Declaration

static func localizedStringWithFormat(_ format: String, _ arguments: CVarArg...) -> String

Instance Methods

func +(_:rhs:)

Declaration

func +(lhs: String, rhs: String) -> String
func +=(_:rhs:)

Declaration

func +=(lhs: inout String, rhs: String)
func <(_:rhs:)

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.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func <(lhs: String, rhs: String) -> Bool
func ==(_:rhs:)

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.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func ==(lhs: String, rhs: String) -> Bool
func addingPercentEncoding(withAllowedCharacters:)

[Foundation] Returns a new string made from the String by replacing all characters not in the specified set with percent encoded characters.

Declaration

func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String?
func addingPercentEscapes(using:)

[Foundation] Returns a representation of the String using a given encoding to determine the percent escapes necessary to convert the String into a legal URL string.

Deprecated: Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid..

Declaration

func addingPercentEscapes(using encoding: String.Encoding) -> String?
mutating func append(_: Character)

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 🌍"

c: The character to append to the string.

Declaration

mutating func append(_ c: Character)
mutating func append(_: String)

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"

other: Another string.

Declaration

mutating func append(_ other: String)
mutating func append(contentsOf:)

Appends the characters in the given sequence to the string.

newElements: A sequence of characters.

Declaration

mutating func append<S : Sequence where S.Iterator.Element == Character>(contentsOf newElements: S)
func appending(_:)

[Foundation] Returns a new string made by appending a given string to the String.

Declaration

func appending(_ aString: String) -> String
func appendingFormat(_:_:)

[Foundation] Returns a string made by appending to the String a string constructed from a given format string and the following arguments.

Declaration

func appendingFormat(_ format: String, _ arguments: CVarArg...) -> String
func applyingTransform(_:reverse:)

[Foundation] Perform string transliteration.

Declaration

func applyingTransform(_ transform: StringTransform, reverse: Bool) -> String?
func cString(using:)

[Foundation] Returns a representation of the String as a C string using a given encoding.

Declaration

func cString(using encoding: String.Encoding) -> [CChar]?
func canBeConverted(to:)

[Foundation] Returns a Boolean value that indicates whether the String can be converted to a given encoding without loss of information.

Declaration

func canBeConverted(to encoding: String.Encoding) -> Bool
func capitalized(with:)

[Foundation] Returns a capitalized representation of the String using the specified locale.

Declaration

func capitalized(with locale: Locale?) -> String
func caseInsensitiveCompare(_:)

[Foundation] Returns the result of invoking compare:options: with NSCaseInsensitiveSearch as the only option.

Declaration

func caseInsensitiveCompare(_ aString: String) -> ComparisonResult
func commonPrefix(with:options:)

[Foundation] Returns a string containing characters the String and a given string have in common, starting from the beginning of each up to the first characters that aren't equivalent.

Declaration

func commonPrefix(with aString: String, options: CompareOptions = default) -> String
func compare(_:options:range:locale:)

[Foundation] Compares the string using the specified options and returns the lexical ordering for the range.

Declaration

func compare(_ aString: String, options mask: CompareOptions = default, range: Range<Index>? = default, locale: Locale? = default) -> ComparisonResult
func completePath(into:caseSensitive:matchesInto:filterTypes:)

[Foundation] Interprets the String as a path in the file system and attempts to perform filename completion, returning a numeric value that indicates whether a match was possible, and by reference the longest path that matches the String. Returns the actual number of matching paths.

Declaration

func completePath(into outputName: UnsafeMutablePointer<String>? = default, caseSensitive: Bool, matchesInto outputArray: UnsafeMutablePointer<[String]>? = default, filterTypes: [String]? = default) -> Int
func components(separatedBy: CharacterSet)

[Foundation] Returns an array containing substrings from the String that have been divided by characters in a given set.

Declaration

func components(separatedBy separator: CharacterSet) -> [String]
func components(separatedBy: String)

[Foundation] Returns an array containing substrings from the String that have been divided by a given separator.

Declaration

func components(separatedBy separator: String) -> [String]
func contains(_:)

[Foundation] Returns true iff other is non-empty and contained within self by case-sensitive, non-literal search.

Equivalent to self.rangeOfString(other) != nil

Declaration

func contains(_ other: String) -> Bool
func data(using:allowLossyConversion:)

[Foundation] Returns a Data containing a representation of the String encoded using a given encoding.

Declaration

func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
func distance(from:to:)

Returns the distance between two indices.

Parameters: start: A valid index of the collection. end: Another valid index of the collection. If end is equal to start, the result is zero. Returns: The distance between start and end.

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

Declaration

func distance(from start: String.Index, to end: String.Index) -> String.IndexDistance
func enumerateLines(_ body: (line: String,:)

[Foundation] Enumerates all the lines in a string.

Declaration

func enumerateLines(_ body: (line: String, stop: inout Bool) -> ())
func enumerateLinguisticTags(in:scheme:options:orthography:_:)

[Foundation] Performs linguistic analysis on the specified string by enumerating the specific range of the string, providing the Block with the located tags.

Declaration

func enumerateLinguisticTags(in range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = default, orthography: NSOrthography? = default, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> ())
func enumerateSubstrings(in:options:_ body: (substring: String?, substringRange: Range<Index>,:)

[Foundation] Enumerates the substrings of the specified type in the specified range of the string.

Declaration

func enumerateSubstrings(in range: Range<Index>, options opts: EnumerationOptions = default, _ body: (substring: String?, substringRange: Range<Index>, enclosingRange: Range<Index>, inout Bool) -> ())
func folding(_:locale:)

[Foundation] Returns a string with the given character folding options applied.

Declaration

func folding(_ options: CompareOptions = default, locale: Locale?) -> String
func getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)

[Foundation] Writes the given range of characters into buffer in a given encoding, without any allocations. Does not NULL-terminate.

buffer: A buffer into which to store the bytes from the receiver. The returned bytes are not NUL-terminated.

maxBufferCount: The maximum number of bytes to write to buffer.

usedBufferCount: The number of bytes used from buffer. Pass nil if you do not need this value.

encoding: The encoding to use for the returned bytes.

options: A mask to specify options to use for converting the receiver's contents to encoding (if conversion is necessary).

range: The range of characters in the receiver to get.

leftover: The remaining range. Pass nil If you do not need this value.

Returns: true iff some characters were converted.

Note: Conversion stops when the buffer fills or when the conversion isn't possible due to the chosen encoding.

Note: will get a maximum of min(buffer.count, maxLength) bytes.

Declaration

func getBytes(_ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: EncodingConversionOptions = default, range: Range<Index>, remaining leftover: UnsafeMutablePointer<Range<Index>>) -> Bool
func getCString(_:maxLength:encoding:)

[Foundation] Converts the String's content to a given encoding and stores them in a buffer. Note: will store a maximum of min(buffer.count, maxLength) bytes.

Declaration

func getCString(_ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding) -> Bool
func getLineStart(_:end:contentsEnd:for:)

[Foundation] Returns by reference the beginning of the first line and the end of the last line touched by the given range.

Declaration

func getLineStart(_ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: Range<Index>)
func getParagraphStart(_:end:contentsEnd:for:)

[Foundation] Returns by reference the beginning of the first paragraph and the end of the last paragraph touched by the given range.

Declaration

func getParagraphStart(_ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: Range<Index>)
func hasPrefix(_:)

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

The comparison is both case sensitive and Unicode safe. The case-sensitive comparison will only match strings whose corresponding characters have the same case.

let cafe = "Café du Monde"

// Case sensitive
print(cafe.hasPrefix("café"))
// Prints "false"

The Unicode-safe comparison matches Unicode scalar values rather than the code points used to compose them. The example below uses two strings with different forms of the "é" character---the first uses the composed form and the second uses the decomposed form.

// Unicode safe
let composedCafe = "Café"
let decomposedCafe = "Cafe\u{0301}"

print(cafe.hasPrefix(composedCafe))
// Prints "true"
print(cafe.hasPrefix(decomposedCafe))
// Prints "true"

prefix: A possible prefix to test against this string. Returns: true if the string begins with prefix, otherwise, false.

Declaration

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

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

The comparison is both case sensitive and Unicode safe. The case-sensitive comparison will only match strings whose corresponding characters have the same case.

let plans = "Let's meet at the café"

// Case sensitive
print(plans.hasSuffix("Café"))
// Prints "false"

The Unicode-safe comparison matches Unicode scalar values rather than the code points used to compose them. The example below uses two strings with different forms of the "é" character---the first uses the composed form and the second uses the decomposed form.

// Unicode safe
let composedCafe = "café"
let decomposedCafe = "cafe\u{0301}"

print(plans.hasSuffix(composedCafe))
// Prints "true"
print(plans.hasSuffix(decomposedCafe))
// Prints "true"

suffix: A possible suffix to test against this string. Returns: true if the string ends with suffix, otherwise, false.

Declaration

func hasSuffix(_ suffix: String) -> Bool
func index(_:offsetBy:)

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 endIndex or before the startIndex of this collection.

Parameters: i: A valid index of the collection. n: The distance to offset i. Returns: An index offset by n from the index i. If n is positive, this is the same value as the result of n calls to index(after:). If n is negative, this is the same value as the result of -n calls to index(before:).

See Also: index(_:offsetBy:limitedBy:) Complexity: O(n), where n is the absolute value of n.

Declaration

func index(_ i: String.Index, offsetBy n: String.IndexDistance) -> String.Index
func index(_:offsetBy:limitedBy:)

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 endIndex or before the startIndex of this collection, unless the index passed as limit prevents offsetting beyond those bounds.

Parameters: i: A valid index of the collection. n: The distance to offset i. limit: A valid index of the collection to use as a limit. If n > 0, a limit that is less than i has no effect. Likewise, if n < 0, a limit that is greater than i has no effect. Returns: An index offset by n from the index i, unless that index would be beyond limit in the direction of movement. In that case, the method returns nil.

See Also: index(_:offsetBy:) Complexity: O(n), where n is the absolute value of n.

Declaration

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

Returns the position immediately after the given index.

i: A valid index of the collection. i must be less than endIndex. Returns: The index value immediately after i.

Declaration

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

Declaration

func index(before i: String.Index) -> String.Index
mutating func insert(_:at:)

Inserts a new character at the specified position.

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

Parameters: newElement: The new character to insert into the string. i: A valid index of the string. If i is equal to the string's end index, this methods appends newElement to the string.

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

Declaration

mutating func insert(_ newElement: Character, at i: String.Index)
mutating func insert(contentsOf:at:)

Inserts a collection of characters at the specified position.

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

Parameters: newElements: A collection of Character elements to insert into the string. i: A valid index of the string. If i is equal to the string's end index, this methods appends the contents of newElements to the string.

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

Declaration

mutating func insert<S : Collection where S.Iterator.Element == Character>(contentsOf newElements: S, at i: String.Index)
func lengthOfBytes(using:)

[Foundation] Returns the number of bytes required to store the String in a given encoding.

Declaration

func lengthOfBytes(using encoding: String.Encoding) -> Int
func lineRange(for:)

[Foundation] Returns the range of characters representing the line or lines containing a given range.

Declaration

func lineRange(for aRange: Range<Index>) -> Range<Index>
func linguisticTags(in:scheme:options:orthography:tokenRanges:)

[Foundation] Returns an array of linguistic tags for the specified range and requested tags within the receiving string.

Declaration

func linguisticTags(in range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = default, orthography: NSOrthography? = default, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = default) -> [String]
func localizedCaseInsensitiveCompare(_:)

[Foundation] Compares the string and a given string using a case-insensitive, localized, comparison.

Declaration

func localizedCaseInsensitiveCompare(_ aString: String) -> ComparisonResult
func localizedCaseInsensitiveContains(_:)

[Foundation] Returns true iff other is non-empty and contained within self by case-insensitive, non-literal search, taking into account the current locale.

Locale-independent case-insensitive operation, and other needs, can be achieved by calling rangeOfString(_:options:, range:_locale:_).

Equivalent to

self.rangeOf(
  other, options: .CaseInsensitiveSearch,
  locale: Locale.current()) != nil

Declaration

func localizedCaseInsensitiveContains(_ other: String) -> Bool
func localizedCompare(_:)

[Foundation] Compares the string and a given string using a localized comparison.

Declaration

func localizedCompare(_ aString: String) -> ComparisonResult
func localizedStandardCompare(_:)

[Foundation] Compares strings as sorted by the Finder.

Declaration

func localizedStandardCompare(_ string: String) -> ComparisonResult
func localizedStandardContains(_:)

[Foundation] Returns true if self contains string, taking the current locale into account.

This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

Declaration

func localizedStandardContains(_ string: String) -> Bool
func localizedStandardRange(of:)

[Foundation] Finds and returns the range of the first occurrence of a given string, taking the current locale into account. Returns nil if the string was not found.

This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

Declaration

func localizedStandardRange(of string: String) -> Range<Index>?
func lowercased()

Returns a lowercase version of the string.

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

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

Returns: A lowercase copy of the string.

Complexity: O(n)

Declaration

func lowercased() -> String
func lowercased(with:)

[Foundation] Returns a version of the string with all letters converted to lowercase, taking into account the specified locale.

Declaration

func lowercased(with locale: Locale?) -> String
func maximumLengthOfBytes(using:)

[Foundation] Returns the maximum number of bytes needed to store the String in a given encoding.

Declaration

func maximumLengthOfBytes(using encoding: String.Encoding) -> Int
func padding(toLength:withPad:startingAt:)

[Foundation] Returns a new string formed from the String by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.

Declaration

func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String
func paragraphRange(for:)

[Foundation] Returns the range of characters representing the paragraph or paragraphs containing a given range.

Declaration

func paragraphRange(for aRange: Range<Index>) -> Range<Index>
func propertyList()

[Foundation] Parses the String as a text representation of a property list, returning an NSString, NSData, NSArray, or NSDictionary object, according to the topmost element.

Declaration

func propertyList() -> AnyObject
func propertyListFromStringsFileFormat()

[Foundation] Returns a dictionary object initialized with the keys and values found in the String.

Declaration

func propertyListFromStringsFileFormat() -> [String : String]
func range(of:options:range:locale:)

[Foundation] Finds and returns the range of the first occurrence of a given string within a given range of the String, subject to given options, using the specified locale, if any.

Declaration

func range(of aString: String, options mask: CompareOptions = default, range searchRange: Range<Index>? = default, locale: Locale? = default) -> Range<Index>?
func rangeOfCharacter(from:options:range:)

[Foundation] Finds and returns the range in the String of the first character from a given character set found in a given range with given options.

Declaration

func rangeOfCharacter(from aSet: CharacterSet, options mask: CompareOptions = default, range aRange: Range<Index>? = default) -> Range<Index>?
func rangeOfComposedCharacterSequence(at:)

[Foundation] Returns the range in the String of the composed character sequence located at a given index.

Declaration

func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index>
func rangeOfComposedCharacterSequences(for:)

[Foundation] Returns the range in the string of the composed character sequences for a given range.

Declaration

func rangeOfComposedCharacterSequences(for range: Range<Index>) -> Range<Index>
mutating func remove(at:)

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.characters.index(of: "-") {
    nonempty.remove(at: i)
}
print(nonempty)
// Prints "nonempty"

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

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. Returns: The character that was removed.

Declaration

mutating func remove(at i: String.Index) -> Character
mutating func removeAll(keepingCapacity:)

Replaces this string with the empty string.

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

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

mutating func removeAll(keepingCapacity keepCapacity: Bool = default)
mutating func removeSubrange(_: ClosedRange<String.Index>)

Removes the characters in the given range.

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

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.

Declaration

mutating func removeSubrange(_ bounds: ClosedRange<String.Index>)
mutating func removeSubrange(_: Range<String.Index>)

Removes the characters in the given range.

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

bounds: The range of the elements to remove. The upper and lower bounds of bounds must be valid indices of the string.

Declaration

mutating func removeSubrange(_ bounds: Range<String.Index>)
mutating func replaceSubrange(_: ClosedRange<String.Index>, with: String)

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

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

Parameters: bounds: The range of text to replace. The bounds of the range must be valid indices of the string. newElements: The new text to add to the 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

mutating func replaceSubrange(_ bounds: ClosedRange<String.Index>, with newElements: String)
mutating func replaceSubrange(_: Range<String.Index>, with: String)

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

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

Parameters: bounds: The range of text to replace. The bounds of the range must be valid indices of the string. newElements: The new text to add to the 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

mutating func replaceSubrange(_ bounds: Range<String.Index>, with newElements: String)
mutating func replaceSubrange<C where C : Collection, C.Iterator.Element == Character>(_: ClosedRange<String.Index>, with: C)

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

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

Parameters: bounds: The range of text to replace. The bounds of the range must be valid indices of the string. newElements: The new characters to add to the 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

mutating func replaceSubrange<C where C : Collection, C.Iterator.Element == Character>(_ bounds: ClosedRange<String.Index>, with newElements: C)
mutating func replaceSubrange<C where C : Collection, C.Iterator.Element == Character>(_: Range<String.Index>, with: C)

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

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

Parameters: bounds: The range of text to replace. The bounds of the range must be valid indices of the string. newElements: The new characters to add to the 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

mutating func replaceSubrange<C where C : Collection, C.Iterator.Element == Character>(_ bounds: Range<String.Index>, with newElements: C)
func replacingCharacters(in:with:)

[Foundation] Returns a new string in which the characters in a specified range of the String are replaced by a given string.

Declaration

func replacingCharacters(in range: Range<Index>, with replacement: String) -> String
func replacingOccurrences(of:with:options:range:)

[Foundation] Returns a new string in which all occurrences of a target string in a specified range of the String are replaced by another given string.

Declaration

func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = default, range searchRange: Range<Index>? = default) -> String
func replacingPercentEscapes(using:)

[Foundation] Returns a new string made by replacing in the String all percent escapes with the matching characters as determined by a given encoding.

Deprecated: Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding..

Declaration

func replacingPercentEscapes(using encoding: String.Encoding) -> String?
mutating func reserveCapacity(_:)

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(_:).

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

Complexity: O(n)

Declaration

mutating func reserveCapacity(_ n: Int)
func substring(from:)

[Foundation] Returns a new string containing the characters of the String from the one at a given index to the end.

Declaration

func substring(from index: Index) -> String
func substring(to:)

[Foundation] Returns a new string containing the characters of the String up to, but not including, the one at a given index.

Declaration

func substring(to index: Index) -> String
func substring(with:)

[Foundation] Returns a string object containing the characters of the String that lie within a given range.

Declaration

func substring(with aRange: Range<Index>) -> String
func trimmingCharacters(in:)

[Foundation] Returns a new string made by removing from both ends of the String characters contained in a given character set.

Declaration

func trimmingCharacters(in set: CharacterSet) -> String
func uppercased()

Returns an uppercase version of the string.

The following example transforms a string to uppercase letters:

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

Returns: An uppercase copy of the string.

Complexity: O(n)

Declaration

func uppercased() -> String
func uppercased(with:)

[Foundation] Returns a version of the string with all letters converted to uppercase, taking into account the specified locale.

Declaration

func uppercased(with locale: Locale?) -> String
func withCString(_:)

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

The withCString(_:) method ensures that the sequence's lifetime extends through the execution of f.

f: A closure that takes a pointer to the string's UTF-8 code unit sequence as its sole argument. If the closure has a return value, it is used as the return value of the withCString(_:) method. Returns: The return value of the f closure, if any.

Declaration

func withCString<Result>(_ body: (UnsafePointer<Int8>) throws -> Result) rethrows -> Result
mutating func withMutableCharacters(_:)

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

Do not use the string that is the target of this method inside the closure passed to body, as it may not have its correct value. Instead, use the closure's String.CharacterView argument.

This example below uses the withMutableCharacters(_:) method to truncate the string str at the first space and to return the remainder of the string.

var str = "All this happened, more or less."
let afterSpace = str.withMutableCharacters { chars -> String.CharacterView in
    if let i = chars.index(of: " ") {
        let result = chars.suffix(from: chars.index(after: i))
        chars.removeSubrange(i..<chars.endIndex)
        return result
    }
    return String.CharacterView()
}

print(str)
// Prints "All"
print(String(afterSpace))
// Prints "this happened, more or less."

body: A closure that takes a character view as its argument. Returns: The return value of the body closure, if any, is the return value of this method.

Declaration

mutating func withMutableCharacters<R>(_ body: (inout String.CharacterView) -> R) -> R
mutating func write(_:)

Appends the given string to this string.

other: A string to append.

Declaration

mutating func write(_ other: String)
func write(to:)

Writes the string into the given output stream.

target: An output stream.

Declaration

func write<Target : TextOutputStream>(to target: inout Target)
func write(to:atomically:encoding:)

[Foundation] Writes the contents of the String to the URL specified by url using the specified encoding.

Declaration

func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding) throws
func write(toFile:atomically:encoding:)

[Foundation] Writes the contents of the String to a file at a given path using a given encoding.

Declaration

func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding) throws