String
A Unicode string value that is a collection of characters.
@frozen struct String
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.
Citizens in Swift
Conformances
protocol BidirectionalCollection
A collection that supports backward as well as forward traversal.
protocol CodingKeyRepresentable
A type that can be converted to and from a coding key.
protocol Collection
A sequence whose elements can be traversed multiple times, nondestructively, and accessed by an indexed subscript.
protocol Comparable
A type that can be compared using the relational operators
<
,<=
,>=
, and>
.protocol CustomDebugStringConvertible
A type with a customized textual representation suitable for debugging purposes.
protocol CustomReflectable
A type that explicitly supplies its own mirror.
protocol CustomStringConvertible
A type with a customized textual representation.
protocol Decodable
A type that can decode itself from an external representation.
protocol Encodable
A type that can encode itself to an external representation.
protocol Equatable
A type that can be compared for value equality.
protocol ExpressibleByExtendedGraphemeClusterLiteral
A type that can be initialized with a string literal containing a single extended grapheme cluster.
protocol ExpressibleByStringInterpolation
A type that can be initialized by string interpolation with a string literal that includes expressions.
protocol ExpressibleByStringLiteral
A type that can be initialized with a string literal.
protocol ExpressibleByUnicodeScalarLiteral
A type that can be initialized with a string literal containing a single Unicode scalar value.
protocol Hashable
A type that can be hashed into a
Hasher
to produce an integer hash value.protocol LosslessStringConvertible
A type that can be represented as a string in a lossless, unambiguous way.
protocol MirrorPath
A protocol for legitimate arguments to
Mirror
’sdescendant
method.protocol RangeReplaceableCollection
A collection that supports replacement of an arbitrary subrange of elements with the elements of another collection.
protocol Sendable
A type whose values can safely be passed across concurrency domains by copying.
protocol Sequence
A type that provides sequential, iterated access to its elements.
protocol StringProtocol
A type that can represent a string as a collection of characters.
protocol TextOutputStream
A type that can be the target of text-streaming operations.
protocol TextOutputStreamable
A source of text-streaming operations.
Members
init(
) Creates an empty string.
init(String
.UnicodeScalarView) Creates a string corresponding to the given collection of Unicode scalars.
init(String
.UTF8View) Creates a string corresponding to the given sequence of UTF-8 code units.
init(String
.UTF16View) Creates a string corresponding to the given sequence of UTF-16 code units.
init(Character
) Creates a string containing the given character.
init?(Substring
.UTF8View) Creates a String having the given content.
init?(Substring
.UTF16View) Creates a String having the given content.
init(Substring
.UnicodeScalarView) Creates a String having the given content.
init(Substring
) Creates a new string from the given substring.
init(Unicode
.Scalar) init<S>(S
) Creates a new string containing the characters in the given sequence.
init<S>(S
) Creates a new string containing the characters in the given sequence.
init<T>(T
) Creates an instance from the description of a given
LosslessStringConvertible
instance.init<T>(T, radix: Int, uppercase: Bool
) Creates a string representing the given value in base 10, or some other specified base.
init(cString: UnsafePointer<CChar>
) Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.
init(cString: UnsafePointer<UInt8>
) Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.
init(cString: [CChar]
) init(cString: [UInt8]
) init?<T>(codingKey: T
) init<C, Encoding>(decoding: C, as: Encoding.Type
) Creates a string from the given Unicode code units in the specified encoding.
init<Encoding>(decodingCString: UnsafePointer<Encoding.CodeUnit>, as: Encoding.Type
) Creates a string from the null-terminated sequence of bytes at the given pointer.
init<Encoding>(decodingCString: [Encoding.CodeUnit], as: Encoding.Type
) init<Subject>(describing: Subject
) Creates a string representing the given value.
init<Subject>(describing: Subject
) Creates a string representing the given value.
init<Subject>(describing: Subject
) Creates a string representing the given value.
init<Subject>(describing: Subject
) Creates a string representing the given value.
init(from: Decoder
) throws Creates a new instance by decoding from the given decoder.
init<Subject>(reflecting: Subject
) Creates a string with a detailed representation of the given value, suitable for debugging.
init(repeating: String, count: Int
) Creates a new string representing the given string repeated the specified number of times.
init(repeating: Character, count: Int
) Creates a string representing the given character repeated the specified number of times.
init(stringInterpolation: DefaultStringInterpolation
) Creates a new instance from an interpolated string literal.
init(stringLiteral: String
) Creates an instance initialized to the given string value.
init(unsafeUninitializedCapacity: Int, initializingUTF8With: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows Creates a new string with the specified capacity in UTF-8 code units, and then calls the given closure with a buffer covering the string’s uninitialized memory.
init?(validatingUTF8: UnsafePointer<CChar>
) Creates a new string by copying and validating the null-terminated UTF-8 data referenced by the given pointer.
init?(validatingUTF8: [CChar]
) static func decodeCString<Encoding>(UnsafePointer
<Encoding.CodeUnit>?, as: Encoding.Type, repairingInvalidCodeUnits: Bool) -> (result: String, repairsMade: Bool)? Creates a new string by copying the null-terminated data referenced by the given pointer using the specified encoding.
static func decodeCString<Encoding>([Encoding.CodeUnit], as: Encoding.Type, repairingInvalidCodeUnits: Bool
) -> (result: String, repairsMade: Bool)? var codingKey: CodingKey
var count: Int
The number of characters in a string.
var customMirror: Mirror
A mirror that reflects the
String
instance.var debugDescription: String
A representation of the string that is suitable for debugging.
var description: String
The value of this string.
var endIndex: String.Index
A string’s “past the end” position—that is, the position one greater than the last valid subscript argument.
var isContiguousUTF8: Bool
Returns whether this string is capable of providing access to validly-encoded UTF-8 contents in contiguous memory in O(1) time.
var isEmpty: Bool
A Boolean value indicating whether a string has no characters.
var startIndex: String.Index
The position of the first character in a nonempty string.
var unicodeScalars: String.UnicodeScalarView
The string’s value represented as a collection of Unicode scalar values.
var utf16: String.UTF16View
A UTF-16 encoding of
self
.var utf8: String.UTF8View
A UTF-8 encoding of
self
.var utf8CString: ContiguousArray<CChar>
A contiguously stored null-terminated UTF-8 representation of the string.
subscript(String
.Index) -> Character Accesses the character at the given position.
subscript(Range
<String.Index>) -> Substring static func + (String, String
) -> String static func += (inout String, String
) static func < (String, String
) -> Bool static func == (String, String
) -> Bool static func ~= (String, Substring
) -> Bool func append(Character
) Appends the given character to the string.
func append(String
) Appends the given string to this string.
func append(contentsOf: String
) func append(contentsOf: Substring
) func append<S>(contentsOf: S
) Appends the characters in the given sequence to the string.
func distance(from: String.Index, to: String.Index
) -> Int Returns the distance between two indices.
func encode(to: Encoder
) throws Encodes this value into the given encoder.
func hasPrefix(String
) -> Bool func hasSuffix(String
) -> Bool func hash(into: inout Hasher
) Hashes the essential components of this value by feeding them into the given hasher.
func index(String
.Index, offsetBy: Int) -> String.Index Returns an index that is the specified distance from the given index.
func index(String
.Index, offsetBy: Int, limitedBy: String.Index) -> String.Index? Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.
func index(after: String.Index
) -> String.Index Returns the position immediately after the given index.
func index(before: String.Index
) -> String.Index Returns the position immediately before the given index.
func insert(Character, at: String.Index
) Inserts a new character at the specified position.
func insert<S>(contentsOf: S, at: String.Index
) Inserts a collection of characters at the specified position.
func lowercased(
) -> String Returns a lowercase version of the string.
func makeContiguousUTF8(
) If this string is not contiguous, make it so. If this mutates the string, it will invalidate any pre-existing indices.
func makeIterator(
) -> String.Iterator func max<T>(T, T
) -> T func min<T>(T, T
) -> T func remove(at: String.Index
) -> Character Removes and returns the character at the specified position.
func removeAll(keepingCapacity: Bool
) Replaces this string with the empty string.
func removeSubrange(Range
<String.Index>) Removes the characters in the given range.
func replaceSubrange<C>(Range
<String.Index>, with: C) Replaces the text within the specified bounds with the given characters.
func reserveCapacity(Int
) Reserves enough space in the string’s underlying storage to store the specified number of ASCII characters.
func uppercased(
) -> String Returns an uppercase version of the string.
func withCString<Result>((UnsafePointer<Int8>) throws -> Result
) rethrows -> Result Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of UTF-8 code units.
func withCString<Result, TargetEncoding>(encodedAs: TargetEncoding.Type, (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result
) rethrows -> Result Calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units.
func withUTF8<R>((UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R Runs
body
over the content of this 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.func write(String
) Appends the given string to this string.
func write<Target>(to: inout Target
) Writes the string into the given output stream.
struct Index
A position of a character or code unit in a string.
struct Iterator
struct UTF16View
A view of a string’s contents as a collection of UTF-16 code units.
struct UTF8View
A view of a string’s contents as a collection of UTF-8 code units.
struct UnicodeScalarView
A view of a string’s contents as a collection of Unicode scalar values.
typealias Element
typealias SubSequence
typealias UnicodeScalarIndex
The index type for a string’s
unicodeScalars
view.init(cString: String
) init(cString: inout CChar
) init(cString: inout UInt8
) init<Encoding>(decodingCString: String, as: Encoding.Type
) init<Encoding>(decodingCString: inout Encoding.CodeUnit, as: Encoding.Type
) init?(validatingUTF8: String
) init?(validatingUTF8: inout CChar
) static func decodeCString<Encoding>(inout Encoding
.CodeUnit, as: Encoding.Type, repairingInvalidCodeUnits: Bool) -> (result: String, repairsMade: Bool)? static func decodeCString<Encoding>(String, as: Encoding.Type, repairingInvalidCodeUnits: Bool
) -> (result: String, repairsMade: Bool)? var characters: String
A view of the string’s contents as a collection of characters.
var customPlaygroundQuickLook: _PlaygroundQuickLook
A custom playground Quick Look for the
String
instance.func withMutableCharacters<R>((inout String) -> R
) -> R Applies the given closure to a mutable view of the string’s characters.
typealias CharacterView
A view of a string’s contents as a collection of characters.
typealias IndexDistance
A type that represents the number of steps between two
String.Index
values, where one value is reachable from the other.
Features
var first: Self.Element?
The first element of the collection.
var last: Self.Element?
The last element of the collection.
var lazy: LazySequence<Self>
A sequence containing the same elements as this sequence, but on which some operations, such as
map
andfilter
, are implemented lazily.static func != (Self, Self
) -> Bool static func != <RHS>(Self, RHS
) -> Bool static func + <Other>(Other, Self
) -> Self Creates a new collection by concatenating the elements of a sequence and a collection.
static func + <Other>(Self, Other
) -> Self Creates a new collection by concatenating the elements of a collection and a sequence.
static func + <Other>(Self, Other
) -> Self Creates a new collection by concatenating the elements of two collections.
static func += <Other>(inout Self, Other
) Appends the elements of a sequence to a range-replaceable collection.
static func ... (Self
) -> PartialRangeFrom<Self> Returns a partial range extending upward from a lower bound.
static func ... (Self
) -> PartialRangeThrough<Self> Returns a partial range up to, and including, its upper bound.
static func ... (Self, Self
) -> ClosedRange<Self> Returns a closed range that contains both of its bounds.
static func ..< (Self
) -> PartialRangeUpTo<Self> Returns a partial range up to, but not including, its upper bound.
static func ..< (Self, Self
) -> Range<Self> Returns a half-open range that contains its lower bound but not its upper bound.
static func == <RHS>(Self, RHS
) -> Bool func allSatisfy((Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
func applying(CollectionDifference
<Self.Element>) -> Self? Applies the given difference to this collection.
func compactMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] Returns an array containing the non-
nil
results of calling the given transformation with each element of this sequence.func contains(Self
.Element) -> Bool Returns a Boolean value indicating whether the sequence contains the given element.
func contains(where: (Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
func difference<C>(from: C
) -> CollectionDifference<Self.Element> Returns the difference needed to produce this collection’s ordered elements from the given collection.
func difference<C>(from: C, by: (C.Element, Self.Element) -> Bool
) -> CollectionDifference<Self.Element> Returns the difference needed to produce this collection’s ordered elements from the given collection, using the given predicate as an equivalence test.
func drop(while: (Self.Element) throws -> Bool
) rethrows -> Self.SubSequence Returns a subsequence by skipping elements while
predicate
returnstrue
and returning the remaining elements.func dropFirst(Int
) -> Self.SubSequence Returns a subsequence containing all but the given number of initial elements.
func dropLast(Int
) -> Self.SubSequence Returns a subsequence containing all but the specified number of final elements.
func elementsEqual<OtherSequence>(OtherSequence
) -> Bool Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.
func elementsEqual<OtherSequence>(OtherSequence, by: (Self.Element, OtherSequence.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements in the same order, using the given predicate as the equivalence test.
func enumerated(
) -> EnumeratedSequence<Self> Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.
func filter((Self.Element) throws -> Bool
) rethrows -> Self Returns a new collection of the same type containing, in order, the elements of the original collection that satisfy the given predicate.
func first(where: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the first element of the sequence that satisfies the given predicate.
func firstIndex(of: Self.Element
) -> Self.Index? Returns the first index where the specified value appears in the collection.
func firstIndex(where: (Self.Element) throws -> Bool
) rethrows -> Self.Index? Returns the first index in which an element of the collection satisfies the given predicate.
func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
func forEach((Self.Element) throws -> Void
) rethrows Calls the given closure on each element in the sequence in the same order as a
for
-in
loop.func formIndex(inout Self
.Index, offsetBy: Int) Offsets the given index by the specified distance.
func formIndex(inout Self
.Index, offsetBy: Int, limitedBy: Self.Index) -> Bool Offsets the given index by the specified distance, or so that it equals the given limiting index.
func last(where: (Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the last element of the sequence that satisfies the given predicate.
func lastIndex(of: Self.Element
) -> Self.Index? Returns the last index where the specified value appears in the collection.
func lastIndex(where: (Self.Element) throws -> Bool
) rethrows -> Self.Index? Returns the index of the last element in the collection that matches the given predicate.
func lexicographicallyPrecedes<OtherSequence>(OtherSequence
) -> Bool Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (
<
) to compare elements.func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.
func map<T>((Self.Element) throws -> T
) rethrows -> [T] Returns an array containing the results of mapping the given closure over the sequence’s elements.
func map<T>((Self.Element) throws -> T
) rethrows -> [T] Returns an array containing the results of mapping the given closure over the sequence’s elements.
func max(
) -> Self.Element? Returns the maximum element in the sequence.
func max(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the maximum element in the sequence, using the given predicate as the comparison between elements.
func min(
) -> Self.Element? Returns the minimum element in the sequence.
func min(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> Self.Element? Returns the minimum element in the sequence, using the given predicate as the comparison between elements.
func popLast(
) -> Self.Element? Removes and returns the last element of the collection.
func prefix(Int
) -> Self.SubSequence Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.
func prefix(through: Self.Index
) -> Self.SubSequence Returns a subsequence from the start of the collection through the specified position.
func prefix(upTo: Self.Index
) -> Self.SubSequence Returns a subsequence from the start of the collection up to, but not including, the specified position.
func prefix(while: (Self.Element) throws -> Bool
) rethrows -> Self.SubSequence Returns a subsequence containing the initial elements until
predicate
returnsfalse
and skipping the remaining elements.func randomElement(
) -> Self.Element? Returns a random element of the collection.
func randomElement<T>(using: inout T
) -> Self.Element? Returns a random element of the collection, using the given generator as a source for randomness.
func reduce<Result>(Result, (Result, Self.Element) throws -> Result
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func reduce<Result>(into: Result, (inout Result, Self.Element) throws -> ()
) rethrows -> Result Returns the result of combining the elements of the sequence using the given closure.
func removeLast(
) -> Self.Element Removes and returns the last element of the collection.
func removeLast(Int
) Removes the specified number of elements from the end of the collection.
func reversed(
) -> ReversedCollection<Self> Returns a view presenting the elements of the collection in reverse order.
func shuffled(
) -> [Self.Element] Returns the elements of the sequence, shuffled.
func shuffled<T>(using: inout T
) -> [Self.Element] Returns the elements of the sequence, shuffled using the given generator as a source for randomness.
func sorted(
) -> [Self.Element] Returns the elements of the sequence, sorted.
func sorted(by: (Self.Element, Self.Element) throws -> Bool
) rethrows -> [Self.Element] Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.
func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Self.Element) throws -> Bool
) rethrows -> [Self.SubSequence] Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.
func split(separator: Self.Element, maxSplits: Int, omittingEmptySubsequences: Bool
) -> [Self.SubSequence] Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.
func starts<PossiblePrefix>(with: PossiblePrefix
) -> Bool Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.
func starts<PossiblePrefix>(with: PossiblePrefix, by: (Self.Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> Bool Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.
func suffix(Int
) -> Self.SubSequence Returns a subsequence, up to the given maximum length, containing the final elements of the collection.
func suffix(from: Self.Index
) -> Self.SubSequence Returns a subsequence from the specified position to the end of the collection.
func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] func index(of: Self.Element
) -> Self.Index? Returns the first index where the specified value appears in the collection.
Available in _RegexParser
Members
Available in RegexBuilder
Conformances
protocol RegexComponent
A type that represents a regular expression.
Members
Available in Foundation
Conformances
protocol CVarArg
A type whose instances can be encoded, and appropriately passed, as elements of a C
va_list
.
Members
init(NSString
) init(Slice
<AttributedString.CharacterView>) init?<S>(bytes: S, encoding: String.Encoding
) Creates a new string equivalent to the given bytes interpreted in the specified encoding.
init?(bytesNoCopy: UnsafeMutableRawPointer, length: Int, encoding: String.Encoding, freeWhenDone: Bool
) Creates a new string that contains the specified number of bytes from the given buffer, interpreted in the specified encoding, and optionally frees the buffer.
init?(cString: UnsafePointer<CChar>, encoding: String.Encoding
) Produces a string by copying the null-terminated bytes in a given C array, interpreted according to a given encoding.
init?(cString: [CChar], encoding: String.Encoding
) Produces a string by copying the null-terminated bytes in a given array, interpreted according to a given encoding.
init(contentsOf: URL
) throws init(contentsOf: URL, encoding: String.Encoding
) throws Produces a string created by reading data from a given URL interpreted using a given encoding. Errors are written into the inout
error
argument.init(contentsOf: URL, usedEncoding: inout String.Encoding
) throws 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.init(contentsOfFile: String
) throws init(contentsOfFile: String, encoding: String.Encoding
) throws Produces a string created by reading data from the file at a given path interpreted using a given encoding.
init(contentsOfFile: String, usedEncoding: inout String.Encoding
) throws 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.
init?(data: Data, encoding: String.Encoding
) Returns a
String
initialized by converting givendata
into Unicode characters using a givenencoding
.init(format: String, CVarArg...
) Returns a
String
object initialized by using a given format string as a template into which the remaining argument values are substituted.init(format: String, arguments: [CVarArg]
) 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.init(format: String, locale: Locale?, CVarArg...
) 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.init(format: String, locale: Locale?, arguments: [CVarArg]
) 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.init(utf16CodeUnits: UnsafePointer<unichar>, count: Int
) Creates a new string that contains the specified number of characters from the given C array of Unicode characters.
init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone: Bool
) Creates a new string that contains the specified number of characters from the given C array of UTF-16 code units.
init?(utf8String: UnsafePointer<CChar>
) Creates a string by copying the data from a given null-terminated C array of UTF8-encoded bytes.
init?(utf8String: [CChar]
) Creates a string by copying the data from a given null-terminated array of UTF8-encoded bytes.
static var availableStringEncodings: [String.Encoding]
An array of the encodings that strings support in the application’s environment.
static var defaultCStringEncoding: String.Encoding
The C-string encoding assumed for any method accepting a C string as an argument.
static func localizedName(of: String.Encoding
) -> String Returns a human-readable string giving the name of the specified encoding.
static func localizedStringWithFormat(String, CVarArg...
) -> String 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.
struct Encoding
typealias CompareOptions
typealias EncodingConversionOptions
typealias EnumerationOptions
init?(cString: String, encoding: String.Encoding
) init?(cString: inout CChar, encoding: String.Encoding
) init?(utf8String: String
) init?(utf8String: inout CChar
)
Extension in BSON
Conformances
Features
Extension in ConsoleKit
Members
func consoleText(ConsoleStyle
) -> ConsoleText Converts this
String
toConsoleText
.func consoleText(color: ConsoleColor?, background: ConsoleColor?, isBold: Bool
) -> ConsoleText Converts this
String
toConsoleText
.
Extension in MultipartKit
Conformances
Members
Extension in RoutingKit
Members
var pathComponents: [PathComponent]
Converts a string into
[PathComponent]
.
Extension in ArgumentParser
Conformances
protocol ExpressibleByArgument
A type that can be expressed as a command-line argument.
Members
Extension in SwiftASN1
Members
init(ASN1UTF8String
) Construct a
String
from anASN1UTF8String
.init(ASN1PrintableString
) Construct a
String
from anASN1PrintableString
.init(ASN1IA5String
) Construct a
String
from anASN1IA5String
.
Extension in JSONDecoding
Conformances
protocol JSONDecodable
A type that can be decoded from a JSON variant value.
protocol JSONStringDecodable
A type that can be decoded from a JSON UTF-8 string. This protocol exists to allow types that also conform to
LosslessStringConvertible
to opt-in to automaticJSONDecodable
conformance as well.
Members
Extension in JSONEncoding
Conformances
protocol JSONEncodable
A type that can be encoded to a JSON variant value.
Members
func encoded(as: JSON.Type
) -> JSON Encodes this string as a value of
JSON.string(_:)
.
Extension in BSONTypes
Members
init(bson: BSON.UTF8View<some BidirectionalCollection<UInt8>>
) Copies and validates the backing storage of the given UTF-8 string to a native Swift string, repairing invalid code units if needed.
Extension in BSONDecoding
Conformances
protocol BSONDecodable
A type that can be decoded from a BSON variant value backed by some type of storage not particular to the decoded type.
protocol BSONStringDecodable
A type that can be decoded from a BSON UTF-8 string. Javascript sources count as UTF-8 strings, from the perspective of this protocol. This protocol exists to allow types that also conform to
LosslessStringConvertible
to opt-in to automaticBSONDecodable
conformance as well.
Extension in BSONEncoding
Conformances
protocol BSONEncodable
A type that can be encoded to a BSON variant value.
Members
func encode(to: inout BSON.Field
) Encodes this string as a value of type
BSON.string
.
Extension in _NIOBase64
Members
init<Buffer>(base64Encoding: Buffer
) Base64 encode a collection of UInt8 to a string, without the use of Foundation.
func base64Decoded(
) throws -> [UInt8]
Extension in NIOCore
Members
init(buffer: ByteBuffer
) Creates a
String
from a givenByteBuffer
. The entire readable portion of the buffer will be read.
Extension in SwiftSyntax
Members
init(syntaxText: SyntaxText
) Creates a
String
from aSyntaxText
.func withSyntaxText<R>((SyntaxText) throws -> R
) rethrows -> R Runs
body
with aSyntaxText
that refers the contiguous memory of this string. LikeString.withUTF8(_:)
, this may mutate the string if this string was not contiguous.
Extension in SwiftSyntaxBuilder
Conformances
protocol ExpressibleByLiteralSyntax
A Swift type whose value can be represented directly in source code by a Swift literal.
Members
Extension in _SwiftSyntaxTestSupport
Members
Extension in SystemPackage
Members
init(decoding: FilePath.Root
) On Unix, creates the string
"/"
init(decoding: FilePath.Component
) Creates a string by interpreting the path component’s content as UTF-8 on Unix and UTF-16 on Windows.
init(decoding: FilePath
) Creates a string by interpreting the file path’s content as UTF-8 on Unix and UTF-16 on Windows.
init(platformString: UnsafePointer<CInterop.PlatformChar>
) Creates a string by interpreting the null-terminated platform string as UTF-8 on Unix and UTF-16 on Windows.
init(platformString: [CInterop.PlatformChar]
) Creates a string by interpreting the null-terminated platform string as UTF-8 on Unix and UTF-16 on Windows.
init?(validating: FilePath.Root
) On Unix, creates the string
"/"
init?(validating: FilePath.Component
) Creates a string from a path component, validating its contents as UTF-8 on Unix and UTF-16 on Windows.
init?(validating: FilePath
) Creates a string from a file path, validating its contents as UTF-8 on Unix and UTF-16 on Windows.
init?(validatingPlatformString: UnsafePointer<CInterop.PlatformChar>
) Creates a string by interpreting the null-terminated platform string as UTF-8 on Unix and UTF-16 on Windows.
init?(validatingPlatformString: [CInterop.PlatformChar]
) Creates a string by interpreting the null-terminated platform string as UTF-8 on Unix and UTF-16 on Windows.
func withPlatformString<Result>((UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result Calls the given closure with a pointer to the contents of the string, represented as a null-terminated platform string.
init(FilePath
) init(platformString: String
) init(platformString: inout CInterop.PlatformChar
) init?(validatingPlatformString: String
) init?(validatingPlatformString: inout CInterop.PlatformChar
) init?(validatingUTF8: FilePath
)
Extension in HTMLStreaming
Conformances
Extension in JSONDecoding
Conformances
protocol JSONDecodable
A type that can be decoded from a JSON variant value.
protocol JSONStringDecodable
A type that can be decoded from a JSON UTF-8 string. This protocol exists to allow types that also conform to
LosslessStringConvertible
to opt-in to automaticJSONDecodable
conformance as well.
Members
Extension in JSONEncoding
Conformances
Extension in Vapor
Conformances
protocol AsyncRequestDecodable
Can convert
Request
to aSelf
.protocol AsyncResponseEncodable
Can convert
self
to aResponse
.protocol Content
Convertible to / from content in an HTTP message.
protocol RequestDecodable
Can convert
Request
to aSelf
.protocol ResponseEncodable
Can convert
self
to aResponse
.
Members
static var defaultContentType: HTTPMediaType
func base32Bytes(
) -> [UInt8] func base32String(
) -> String func base64Bytes(
) -> [UInt8] func base64String(
) -> String func bcryptBase64Bytes(
) -> [UInt8] func bcryptBase64String(
) -> String func encodeResponse(for: Request
) -> EventLoopFuture<Response> func encodeResponse(for: Request
) async throws -> Response func finished(with: String
) -> String
Features
func encodeResponse(status: HTTPStatus, headers: HTTPHeaders, for: Request
) -> EventLoopFuture<Response> Asynchronously encodes
Self
into aResponse
, setting the supplied status and headers.