StringProtocol

protocol StringProtocol

A type that can represent a string as a collection of characters.

Do not declare new conformances to StringProtocol. Only the String and Substring types in the standard library are valid conforming types.

Inheritance BidirectionalCollection, Collection, Comparable, CustomStringConvertible, Equatable, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByStringLiteral, ExpressibleByUnicodeScalarLiteral, Hashable, LosslessStringConvertible, Sequence, TextOutputStream, TextOutputStreamable View Protocol Hierarchy →
Associated Types
UTF8View : Collection
UTF16View : BidirectionalCollection
UnicodeScalarView : BidirectionalCollection
Element : associatedtype Index
SubSequence : associatedtype Indices
Index : Comparable

A type that represents a position in the collection.

Valid indices consist of the position of every element and a "past the end" position that's not valid for use as a subscript argument.

Iterator = IndexingIterator<Self>

A type that provides the collection's iteration interface and encapsulates its iteration state.

By default, a collection conforms to the Sequence protocol by supplying IndexingIterator as its associated Iterator type.

Indices : Collection = DefaultIndices<Self>

A type that represents the indices that are valid for subscripting the collection, in ascending order.

IndexDistance = Int

Deprecated: all index distances are now of type Int.

ExtendedGraphemeClusterLiteralType : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral

A type that represents an extended grapheme cluster literal.

Valid types for ExtendedGraphemeClusterLiteralType are Character, String, and StaticString.

StringLiteralType : _ExpressibleByBuiltinStringLiteral

A type that represents a string literal.

Valid types for StringLiteralType are String and StaticString.

UnicodeScalarLiteralType : _ExpressibleByBuiltinUnicodeScalarLiteral

A type that represents a Unicode scalar literal.

Valid types for UnicodeScalarLiteralType are Unicode.Scalar, Character, String, and StaticString.

Import import Swift

Initializers

init(cString:) Required

Creates a string from the null-terminated, UTF-8 encoded sequence of bytes at the given pointer.

nullTerminatedUTF8: A pointer to a sequence of contiguous, UTF-8 encoded bytes ending just before the first zero byte.

Declaration

init(cString nullTerminatedUTF8: UnsafePointer<CChar>)
init(decoding:as:) Required

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

Parameters: codeUnits: A collection of code units encoded in the encoding specified in sourceEncoding. sourceEncoding: The encoding in which codeUnits should be interpreted.

Declaration

init<C, Encoding>(decoding codeUnits: C, as sourceEncoding: Encoding.Type)
init(decodingCString:as:) Required

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

Parameters: nullTerminatedCodeUnits: A pointer to a sequence of contiguous code units in the encoding specified in sourceEncoding, ending just before the first zero code unit. sourceEncoding: The encoding in which the code units should be interpreted.

Declaration

init<Encoding>(decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type)
init(extendedGraphemeClusterLiteral:) Required

Creates an instance initialized to the given value.

value: The value of the new instance.

Declaration

init(extendedGraphemeClusterLiteral value: Self.ExtendedGraphemeClusterLiteralType)

Declared In

ExpressibleByExtendedGraphemeClusterLiteral
init(stringLiteral:) Required

Creates an instance initialized to the given string value.

value: The value of the new instance.

Declaration

init(stringLiteral value: Self.StringLiteralType)

Declared In

ExpressibleByStringLiteral
init(unicodeScalarLiteral:) Required

Creates an instance initialized to the given value.

value: The value of the new instance.

Declaration

init(unicodeScalarLiteral value: Self.UnicodeScalarLiteralType)

Declared In

ExpressibleByUnicodeScalarLiteral
init?(_:) Required

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

Declaration

init?(_ description: String)

Declared In

LosslessStringConvertible

Instance Variables

var unicodeScalars: Self.UnicodeScalarView Required

Declaration

var unicodeScalars: Self.UnicodeScalarView { get }
var utf8: Self.UTF8View Required

Declaration

var utf8: Self.UTF8View { get }
var utf16: Self.UTF16View Required

Declaration

var utf16: Self.UTF16View { get }
var endIndex: Self.Index Required

Declaration

var endIndex: Self.Index { get }

Declared In

BidirectionalCollection , Collection
var indices: Self.Indices Required

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: Self.Indices { get }

Declared In

BidirectionalCollection , Collection
var last: Self.Element?

The last element of the collection.

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

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

Complexity: O(1)

Declaration

var last: Self.Element? { get }

Declared In

BidirectionalCollection
var startIndex: Self.Index Required

Declaration

var startIndex: Self.Index { get }

Declared In

BidirectionalCollection , Collection
var count: Int

The number of elements in the collection.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Unless the collection guarantees random-access performance, calculating count can be an O(n) operation.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var count: Int { get }

Declared In

Collection
var first: Self.Element?

The first element of the collection.

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

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

Declaration

var first: Self.Element? { get }

Declared In

Collection
var isEmpty: Bool

A Boolean value indicating whether the collection is empty.

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

let horseName = "Silver"
if horseName.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}
// Prints "Hi ho, Silver!"

Complexity: O(1)

Declaration

var isEmpty: Bool { get }

Declared In

Collection
var description: String Required

A textual representation of this instance.

Calling this property directly is discouraged. Instead, convert an instance of any type to a string by using the String(describing:) initializer. This initializer works with any type, and uses the custom description property for types that conform to CustomStringConvertible:

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 }

Declared In

CustomStringConvertible
var hashValue: Int

The 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 }

Declared In

Hashable
var underestimatedCount: Int

A value less than or equal to the number of elements in the sequence, calculated nondestructively.

The default implementation returns 0. If you provide your own implementation, make sure to compute the value nondestructively.

Complexity: O(1), except if the sequence also conforms to Collection. In this case, see the documentation of Collection.underestimatedCount.

Declaration

var underestimatedCount: Int { get }

Declared In

Sequence

Subscripts

subscript(_: Self.Index) Required

Declaration

subscript(position: Self.Index) -> Self.Element { get }

Declared In

BidirectionalCollection, Collection
subscript(_: Range<Self.Index>) Required

Accesses a contiguous subrange of the collection's elements.

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

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

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

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// Prints "Evarts"

bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Declaration

subscript(bounds: Range<Self.Index>) -> Self.SubSequence { get }

Declared In

BidirectionalCollection, Collection

Instance Methods

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: Self, rhs: Self) -> Bool

Declared In

Comparable
func <=(_:rhs:)

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

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

Declaration

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

Declared In

Comparable
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: Self, rhs: Self) -> Bool

Declared In

Equatable
func >(_:rhs:)

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

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

Declaration

func >(lhs: Self, rhs: Self) -> Bool

Declared In

Comparable
func >=(_:rhs:)

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

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

Declaration

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

Declared In

Comparable
func distance(from:to:)

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

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. The result can be negative only if the collection conforms to the BidirectionalCollection protocol.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the resulting distance.

Declaration

func distance(from start: Self.Index, to end: Self.Index) -> Int

Declared In

Collection
func drop(while:)

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.

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

Declaration

func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Declared In

Sequence
func dropFirst(_:)

Returns a subsequence containing all but the given number of initial elements.

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"

n: The number of elements to drop from the beginning of the sequence. n must be greater than or equal to zero. Returns: A subsequence starting after the specified number of elements.

Complexity: O(n), where n is the number of elements to drop from the beginning of the sequence.

Declaration

func dropFirst(_ n: Int) -> Self.SubSequence

Declared In

Sequence
func dropLast(_:)

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

The sequence must be finite. If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"

n: The number of elements to drop off the end of the sequence. n must be greater than or equal to zero. Returns: A subsequence leaving off the specified number of elements.

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

Declaration

func dropLast(_ n: Int) -> Self.SubSequence

Declared In

Sequence
func filter(_:)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

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

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. Returns: An array of the elements that isIncluded allowed.

Declaration

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

Declared In

Sequence
func forEach(_:)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

The two loops in the following example produce the same output:

let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"

numberWords.forEach { word in
    print(word)
}
// Same as above

Using the forEach method is distinct from a for-in loop in two important ways:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
  2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won't skip subsequent calls.

body: A closure that takes an element of the sequence as a parameter.

Declaration

func forEach(_ body: (Self.Element) throws -> Void) rethrows

Declared In

Sequence
func formIndex(after:)

Replaces the given index with its successor.

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

Declaration

func formIndex(after i: inout Self.Index)

Declared In

Collection
func formIndex(before:)

Replaces the given index with its predecessor.

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

Declaration

func formIndex(before i: inout Self.Index)

Declared In

BidirectionalCollection
func hasPrefix(_:)

Declaration

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

Declaration

func hasSuffix(_ prefix: String) -> Bool
func hash(into:)

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

Implement this method to conform to the Hashable protocol. The components used for hashing must be the same as the components compared in your type's == operator implementation. Call hasher.combine(_:) with each of these components.

Important: Never call finalize() on hasher. Doing so may become a compile-time error in the future.

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

Declaration

func hash(into hasher: inout Hasher)

Declared In

Hashable
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 bounds of the collection.

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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:).

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Self.Index, offsetBy n: Int) -> Self.Index

Declared In

Collection
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 bounds of the 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. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Self.Index, offsetBy n: Int, limitedBy limit: Self.Index) -> Self.Index?

Declared In

Collection
func index(after:) Required

Returns the position immediately after the given index.

The successor of an index must be well defined. For an index i into a collection c, calling c.index(after: i) returns the same index every time.

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: Self.Index) -> Self.Index

Declared In

Collection
func index(before:) Required

Returns the position immediately before the given index.

i: A valid index of the collection. i must be greater than startIndex. Returns: The index value immediately before i.

Declaration

func index(before i: Self.Index) -> Self.Index

Declared In

BidirectionalCollection
func lowercased() Required

Declaration

func lowercased() -> String
func makeIterator() Required

Returns an iterator over the elements of the collection.

Declaration

func makeIterator() -> Self.Iterator

Declared In

Collection, Sequence
func map(_:)

Returns an array containing the results of mapping the given closure over the sequence's elements.

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]

transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type. Returns: An array containing the transformed elements of this sequence.

Declaration

func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]

Declared In

Sequence
func prefix(_:)

Returns a subsequence, up to the specified maximum length, containing the initial elements of the sequence.

If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero. Returns: A subsequence starting at the beginning of this sequence with at most maxLength elements.

Declaration

func prefix(_ maxLength: Int) -> Self.SubSequence

Declared In

Sequence
func prefix(through:)

Returns a subsequence from the start of the collection through the specified position.

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection's subscript. The subscript notation is preferred over prefix(through:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"

end: The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property. Returns: A subsequence up to, and including, the end position.

Complexity: O(1)

Declaration

func prefix(through position: Self.Index) -> Self.SubSequence

Declared In

Collection
func prefix(upTo:)

Returns a subsequence from the start of the collection up to, but not including, the specified position.

The resulting subsequence does not include the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, but not including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(upTo: i))
}
// Prints "[10, 20, 30]"

Passing the collection's starting index as the end parameter results in an empty subsequence.

print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[..<i])
}
// Prints "[10, 20, 30]"

end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection. Returns: A subsequence up to, but not including, the end position.

Complexity: O(1)

Declaration

func prefix(upTo end: Self.Index) -> Self.SubSequence

Declared In

Collection
func prefix(while:)

Returns a subsequence containing the initial, consecutive elements that satisfy the given predicate.

The following example uses the prefix(while:) method to find the positive numbers at the beginning of the numbers array. Every element of numbers up to, but not including, the first negative value is included in the result.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let positivePrefix = numbers.prefix(while: { $0 > 0 })
// positivePrefix == [3, 7, 4]

If predicate matches every element in the sequence, the resulting sequence contains every element of the sequence.

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result. Returns: A subsequence of the initial, consecutive elements that satisfy predicate.

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

Declaration

func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Declared In

Sequence
func randomElement(using:)

Returns a random element of the collection, using the given generator as a source for randomness.

You use this method to select a random element from a collection when you are using a custom random number generator. For example, call randomElement(using:) to select a random element from an array of names.

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement(using: &myGenerator)!
// randomName == "Amani"

generator: The random number generator to use when choosing a random element. Returns: A random element from the collection. If the collection is empty, the method returns nil.

Declaration

func randomElement<T>(using generator: inout T) -> Self.Element? where T : RandomNumberGenerator

Declared In

Collection
func split(_:omittingEmptySubsequences:whereSeparator:)

Returns the longest possible subsequences of the sequence, in order, that don't contain elements satisfying the given predicate.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " })
          .map(String.init))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(
    line.split(maxSplits: 1, whereSeparator: { $0 == " " })
        .map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.split(omittingEmptySubsequences: false,
                 whereSeparator: { $0 == " " })
     ).map(String.init))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Parameters: maxSplits: The maximum number of times to split the sequence, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original sequence containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the isSeparator predicate and for each element at the start or end of the sequence satisfying the isSeparator predicate. If true, only nonempty subsequences are returned. The default value is true. isSeparator: A closure that returns true if its argument should be used to split the sequence; otherwise, false. Returns: An array of subsequences, split from this sequence's elements.

Declaration

func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]

Declared In

Sequence
func suffix(_:)

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

The sequence must be finite. If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero. Returns: A subsequence terminating at the end of this sequence with at most maxLength elements.

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

Declaration

func suffix(_ maxLength: Int) -> Self.SubSequence

Declared In

Sequence
func suffix(from:)

Returns a subsequence from the specified position to the end of the collection.

The following example searches for the index of the number 40 in an array of integers, and then prints the suffix of the array starting at that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.suffix(from: i))
}
// Prints "[40, 50, 60]"

Passing the collection's endIndex as the start parameter results in an empty subsequence.

print(numbers.suffix(from: numbers.endIndex))
// Prints "[]"

Using the suffix(from:) method is equivalent to using a partial range from the index as the collection's subscript. The subscript notation is preferred over suffix(from:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[i...])
}
// Prints "[40, 50, 60]"

start: The index at which to start the resulting subsequence. start must be a valid index of the collection. Returns: A subsequence starting at the start position.

Complexity: O(1)

Declaration

func suffix(from start: Self.Index) -> Self.SubSequence

Declared In

Collection
func uppercased() Required

Declaration

func uppercased() -> String
func withCString(_:) Required

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

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

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

Declaration

func withCString<Result>(_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result
func withCString(encodedAs:_:) Required

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

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

Parameters: body: A closure with a pointer parameter that points to a null-terminated sequence of code units. If body has a return value, that value is also used as the return value for the withCString(encodedAs:_:) method. The pointer argument is valid only for the duration of the method's execution. targetEncoding: The encoding in which the code units should be interpreted. Returns: The return value, if any, of the body closure parameter.

Declaration

func withCString<Result, Encoding>(encodedAs targetEncoding: Encoding.Type, _ body: (UnsafePointer<Encoding.CodeUnit>) throws -> Result) rethrows -> Result where Encoding : _UnicodeEncoding
mutating func write(_:) Required

Appends the given string to the stream.

Declaration

mutating func write(_ string: String)

Declared In

TextOutputStream
func write(to:) Required

Writes a textual representation of this instance into the given output stream.

Declaration

func write<Target>(to target: inout Target)

Declared In

TextOutputStreamable

Default Implementations

var count: Int

The number of elements in the collection.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Unless the collection guarantees random-access performance, calculating count can be an O(n) operation.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var count: Int { get }

Declared In

BidirectionalCollection , Collection
var first: Self.Element?

The first element of the collection.

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

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

Declaration

var first: Self.Element? { get }

Declared In

BidirectionalCollection , Collection
var hashValue: Int

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

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

Declaration

var hashValue: Int { get }
var isEmpty: Bool

A Boolean value indicating whether the collection is empty.

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

let horseName = "Silver"
if horseName.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}
// Prints "Hi ho, Silver!")

Complexity: O(1)

Declaration

var isEmpty: Bool { get }

Declared In

BidirectionalCollection , Collection
var last: Self.Element?

The last element of the collection.

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

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

Declaration

var last: Self.Element? { get }

Declared In

BidirectionalCollection
var lazy: LazyCollection<Self>

A view onto this collection that provides lazy implementations of normally eager operations, such as map and filter.

Use the lazy property when chaining operations to prevent intermediate operations from allocating storage, or when you only need a part of the final collection to avoid unnecessary computation.

Declaration

var lazy: LazyCollection<Self> { get }

Declared In

BidirectionalCollection , Collection
var underestimatedCount: Int

A value less than or equal to the number of elements in the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var underestimatedCount: Int { get }

Declared In

BidirectionalCollection , Collection , Sequence
subscript(_: (UnboundedRange_)

Declaration

subscript(x: (UnboundedRange_) -> ()) -> Self.SubSequence { get }

Declared In

BidirectionalCollection, Collection
subscript<R>(_: R)

Accesses the contiguous subrange of the collection's elements specified by a range expression.

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

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

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// "Evarts"

Always use the slice's startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice's indices may result in a runtime error, even if that index is valid for the original collection.

print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"

print(streetsSlice[0])
// error: Index out of bounds

bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

subscript<R>(r: R) -> Self.SubSequence where R : RangeExpression, Self.Index == R.Bound { get }

Declared In

BidirectionalCollection, Collection
func !=(_:rhs:)

Declaration

func !=<S>(lhs: Self, rhs: S) -> Bool where S : StringProtocol

Declared In

StringProtocol, Comparable, Hashable, Equatable
prefix func ...(_: Self)

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

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

let throughFive = ...5.0

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

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

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[...3])
// Prints "[10, 20, 30, 40]"

maximum: The upper bound for the range.

Declaration

prefix func ...(maximum: Self) -> PartialRangeThrough<Self>

Declared In

Comparable
func ...(_:maximum:)

Returns a closed range that contains both of its bounds.

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

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

Parameters: minimum: The lower bound for the range. maximum: The upper bound for the range.

Declaration

func ...(minimum: Self, maximum: Self) -> ClosedRange<Self>

Declared In

Comparable
prefix func ..<(_:)

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

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

let upToFive = ..<5.0

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

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

let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[..<3])
// Prints "[10, 20, 30]"

maximum: The upper bound for the range.

Declaration

prefix func ..<(maximum: Self) -> PartialRangeUpTo<Self>

Declared In

Comparable
func ..<(_:maximum:)

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

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

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

Parameters: minimum: The lower bound for the range. maximum: The upper bound for the range.

Declaration

func ..<(minimum: Self, maximum: Self) -> Range<Self>

Declared In

Comparable
func <(_:rhs:)

Declaration

func <<R>(lhs: Self, rhs: R) -> Bool where R : StringProtocol
func <=(_:rhs:)

Declaration

func <=<R>(lhs: Self, rhs: R) -> Bool where R : StringProtocol

Declared In

StringProtocol, Comparable
func ==(_:rhs:)

Declaration

func ==<S>(lhs: Self, rhs: S) -> Bool where S : StringProtocol
func >(_:rhs:)

Declaration

func ><R>(lhs: Self, rhs: R) -> Bool where R : StringProtocol

Declared In

StringProtocol, Comparable
func >=(_:rhs:)

Declaration

func >=<R>(lhs: Self, rhs: R) -> Bool where R : StringProtocol

Declared In

StringProtocol, Comparable
func allSatisfy(_:)

Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition. Returns: true if the sequence contains only elements that satisfy predicate; otherwise, false.

Declaration

func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool

Declared In

BidirectionalCollection, Collection, Sequence
func compactMap(_:)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

Use this method to receive an array of nonoptional values when your transformation produces an optional value.

In this example, note the difference in the result of using map and compactMap with a transformation that returns an optional Int value.

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]

transform: A closure that accepts an element of this sequence as its argument and returns an optional value. Returns: An array of the non-nil results of calling transform with each element of the sequence.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

Declaration

func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Declared In

BidirectionalCollection, Collection, Sequence
func contains(where:)

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

You can use the predicate to check for an element of a type that doesn't conform to the Equatable protocol, such as the HTTPResponse enumeration in this example.

enum HTTPResponse {
    case ok
    case error(Int)
}

let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
    if case .error = element {
        return true
    } else {
        return false
    }
}
// 'hadError' == true

Alternatively, a predicate can be satisfied by a range of Equatable elements or a general condition. This example shows how you can check an array for an expense greater than $100.

let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 }
// 'hasBigPurchase' == true

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: true if the sequence contains an element that satisfies predicate; otherwise, false.

Declaration

func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool

Declared In

BidirectionalCollection, Collection, Sequence
func distance(from: Self.Index, to: Self.Index)

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

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. The result can be negative only if the collection conforms to the BidirectionalCollection protocol.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the resulting distance.

Declaration

func distance(from start: Self.Index, to end: Self.Index) -> Int

Declared In

BidirectionalCollection, Collection
func distance(from:to:)

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

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. The result can be negative only if the collection conforms to the BidirectionalCollection protocol.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the resulting distance.

Declaration

func distance(from start: Self.Index, to end: Self.Index) -> Int

Declared In

BidirectionalCollection
func distance<T>(from: Self.Index, to: Self.Index)

Deprecated: all index distances are now of type Int.

Declaration

func distance<T>(from start: Self.Index, to end: Self.Index) -> T where T : BinaryInteger

Declared In

BidirectionalCollection, Collection
func drop(while:)

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be skipped or false if it should be included. Once the predicate returns false it will not be called again.

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

Declaration

func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func dropFirst()

Returns a subsequence containing all but the first element of the sequence.

The following example drops the first element from an array of integers.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst())
// Prints "[2, 3, 4, 5]"

If the sequence has no elements, the result is an empty subsequence.

let empty: [Int] = []
print(empty.dropFirst())
// Prints "[]"

Returns: A subsequence starting after the first element of the sequence.

Complexity: O(1)

Declaration

func dropFirst() -> Self.SubSequence

Declared In

BidirectionalCollection, Collection, Sequence
func dropFirst(_:)

Returns a subsequence containing all but the given number of initial elements.

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"

n: The number of elements to drop from the beginning of the collection. n must be greater than or equal to zero. Returns: A subsequence starting after the specified number of elements.

Complexity: O(n), where n is the number of elements to drop from the beginning of the collection.

Declaration

func dropFirst(_ n: Int) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func dropLast()

Returns a subsequence containing all but the last element of the sequence.

The sequence must be finite.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast())
// Prints "[1, 2, 3, 4]"

If the sequence has no elements, the result is an empty subsequence.

let empty: [Int] = []
print(empty.dropLast())
// Prints "[]"

Returns: A subsequence leaving off the last element of the sequence.

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

Declaration

func dropLast() -> Self.SubSequence

Declared In

BidirectionalCollection, Collection, Sequence
func dropLast(_:)

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

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"

n: The number of elements to drop off the end of the collection. n must be greater than or equal to zero. Returns: A subsequence that leaves off n elements from the end.

Complexity: O(n), where n is the number of elements to drop.

Declaration

func dropLast(_ n: Int) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func elementsEqual(_:by:)

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.

At least one of the sequences must be finite.

The predicate must be a equivalence relation over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areEquivalent(a, a) is always true. (Reflexivity)
  • areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry)
  • If areEquivalent(a, b) and areEquivalent(b, c) are both true, then areEquivalent(a, c) is also true. (Transitivity)

Parameters: other: A sequence to compare to this sequence. areEquivalent: A predicate that returns true if its two arguments are equivalent; otherwise, false. Returns: true if this sequence and other contain equivalent items, using areEquivalent as the equivalence test; otherwise, false.

Declaration

func elementsEqual<OtherSequence>(_ other: OtherSequence, by areEquivalent: (Self.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool where OtherSequence : Sequence

Declared In

BidirectionalCollection, Collection, Sequence
func enumerated()

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

This example enumerates the characters of the string "Swift" and prints each character along with its place in the string.

for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"

When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only in instances of zero-based, integer-indexed collections, such as Array and ContiguousArray. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the zip(_:_:) function.

This example iterates over the indices and elements of a set, building a list consisting of indices of names with five or fewer letters.

let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [SetIndex<String>] = []
for (i, name) in zip(names.indices, names) {
    if name.count <= 5 {
        shorterIndices.append(i)
    }
}

Now that the shorterIndices array holds the indices of the shorter names in the names set, you can use those indices to access elements in the set.

for i in shorterIndices {
    print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"

Returns: A sequence of pairs enumerating the sequence.

Declaration

func enumerated() -> EnumeratedSequence<Self>

Declared In

BidirectionalCollection, Collection, Sequence
func filter(_:)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

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

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"

isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. Returns: An array of the elements that isIncluded allowed.

Declaration

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

Declared In

BidirectionalCollection, Collection, Sequence
func first(where:)

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

The following example uses the first(where:) method to find the first negative number in an array of integers:

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
    print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. Returns: The first element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate.

Declaration

func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?

Declared In

BidirectionalCollection, Collection, Sequence
func firstIndex(where:)

Returns the first index in which an element of the collection satisfies the given predicate.

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

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"

predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil.

Declaration

func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?

Declared In

BidirectionalCollection, Collection
func flatMap(_:)

Declaration

func flatMap(_ transform: (Self.Element) throws -> String?) rethrows -> [String]

Declared In

BidirectionalCollection, Collection
func flatMap<ElementOfResult>(_: (Self.Element) throws -> ElementOfResult?)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

Use this method to receive an array of nonoptional values when your transformation produces an optional value.

In this example, note the difference in the result of using map and flatMap with a transformation that returns an optional Int value.

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let flatMapped: [Int] = possibleNumbers.flatMap { str in Int(str) }
// [1, 2, 5]

transform: A closure that accepts an element of this sequence as its argument and returns an optional value. Returns: An array of the non-nil results of calling transform with each element of the sequence.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

Declaration

func flatMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

Declared In

BidirectionalCollection, Collection, Sequence
func flatMap<SegmentOfResult>(_: (Self.Element) throws -> SegmentOfResult)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

Use this method to receive a single-level collection when your transformation produces a sequence or collection for each element.

In this example, note the difference in the result of using map and flatMap with a transformation that returns an array.

let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()).

transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection. Returns: The resulting flattened array.

Complexity: O(m + n), where m is the length of this sequence and n is the length of the result.

Declaration

func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

Declared In

BidirectionalCollection, Collection, Sequence
func forEach(_:)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

The two loops in the following example produce the same output:

let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"

numberWords.forEach { word in
    print(word)
}
// Same as above

Using the forEach method is distinct from a for-in loop in two important ways:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
  2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won't skip subsequent calls.

body: A closure that takes an element of the sequence as a parameter.

Declaration

func forEach(_ body: (Self.Element) throws -> Void) rethrows

Declared In

BidirectionalCollection, Collection, Sequence
func formIndex(_: inout Self.Index, offsetBy: Int)

Offsets the given index by the specified distance.

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

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func formIndex(_ i: inout Self.Index, offsetBy n: Int)

Declared In

BidirectionalCollection, Collection
func formIndex<T>(_: inout Self.Index, offsetBy: T)

Deprecated: all index distances are now of type Int.

Declaration

func formIndex<T>(_ i: inout Self.Index, offsetBy n: T)

Declared In

BidirectionalCollection, Collection
func formIndex(_: inout Self.Index, offsetBy: Int, limitedBy: Self.Index)

Offsets the given index by the specified distance, or so that it equals the given limiting index.

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

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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: true if i has been offset by exactly n steps without going beyond limit; otherwise, false. When the return value is false, the value of i is equal to limit.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func formIndex(_ i: inout Self.Index, offsetBy n: Int, limitedBy limit: Self.Index) -> Bool

Declared In

BidirectionalCollection, Collection
func formIndex<T>(_: inout Self.Index, offsetBy: T, limitedBy: Self.Index)

Deprecated: all index distances are now of type Int.

Declaration

func formIndex<T>(_ i: inout Self.Index, offsetBy n: T, limitedBy limit: Self.Index) -> Bool where T : BinaryInteger

Declared In

BidirectionalCollection, Collection
func formIndex(after:)

Replaces the given index with its successor.

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

Declaration

func formIndex(after i: inout Self.Index)

Declared In

BidirectionalCollection, Collection
func formIndex(before:)

Replaces the given index with its predecessor.

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

Declaration

func formIndex(before i: inout Self.Index)

Declared In

BidirectionalCollection
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>(_ prefix: Prefix) -> Bool where Prefix : StringProtocol
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>(_ suffix: Suffix) -> Bool where Suffix : StringProtocol
func hash(into:)

Declaration

func hash(into hasher: inout Hasher)
func index(_: Self.Index, offsetBy: Int)

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

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

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

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

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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:).

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Self.Index, offsetBy n: Int) -> Self.Index

Declared In

BidirectionalCollection, Collection
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 bounds of the collection.

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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:).

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Self.Index, offsetBy n: Int) -> Self.Index

Declared In

BidirectionalCollection
func index<T>(_: Self.Index, offsetBy: T)

Deprecated: all index distances are now of type Int.

Declaration

func index<T>(_ i: Self.Index, offsetBy n: T) -> Self.Index where T : BinaryInteger

Declared In

BidirectionalCollection, Collection
func index(_: Self.Index, offsetBy: Int, limitedBy: Self.Index)

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

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

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

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

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

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

Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Self.Index, offsetBy n: Int, limitedBy limit: Self.Index) -> Self.Index?

Declared In

BidirectionalCollection, Collection
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 bounds of the 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. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. 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.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n.

Declaration

func index(_ i: Self.Index, offsetBy n: Int, limitedBy limit: Self.Index) -> Self.Index?

Declared In

BidirectionalCollection
func index<T>(_: Self.Index, offsetBy: T, limitedBy: Self.Index)

Deprecated: all index distances are now of type Int.

Declaration

func index<T>(_ i: Self.Index, offsetBy n: T, limitedBy limit: Self.Index) -> Self.Index? where T : BinaryInteger

Declared In

BidirectionalCollection, Collection
func last(where:)

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

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

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let lastNegative = numbers.last(where: { $0 < 0 }) {
    print("The last negative number is \(firstNegative).")
}
// Prints "The last negative number is -6."

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. Returns: The last element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate.

Declaration

func last(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?

Declared In

BidirectionalCollection
func lastIndex(where:)

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

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

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Akosua starts with 'A'!"

predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: The index of the last element in the collection that matches predicate, or nil if no elements match.

Declaration

func lastIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?

Declared In

BidirectionalCollection
func lexicographicallyPrecedes(_:by:)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

Parameters: other: A sequence to compare to this sequence. areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: true if this sequence precedes other in a dictionary ordering as ordered by areInIncreasingOrder; otherwise, false.

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use String APIs that perform localized comparison instead.

Declaration

func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence, by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Bool where OtherSequence : Sequence, Self.Element == OtherSequence.Element

Declared In

BidirectionalCollection, Collection, Sequence
func map(_:)

Returns an array containing the results of mapping the given closure over the sequence's elements.

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]

transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type. Returns: An array containing the transformed elements of this sequence.

Declaration

func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]

Declared In

BidirectionalCollection, Collection, Sequence
@warn_unqualified_access func max(by:)

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

This example shows how to use the max(by:) method on a dictionary to find the key-value pair with the highest value.

let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
// Prints "Optional(("Heliotrope", 296))"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: The sequence's maximum element if the sequence is not empty; otherwise, nil.

Declaration

@warn_unqualified_access func max(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?

Declared In

BidirectionalCollection, Collection, Sequence
func min(by:)

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

This example shows how to use the min(by:) method on a dictionary to find the key-value pair with the lowest value.

let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let leastHue = hues.min { a, b in a.value < b.value }
print(leastHue)
// Prints "Optional(("Coral", 16))"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: The sequence's minimum element, according to areInIncreasingOrder. If the sequence has no elements, returns nil.

Declaration

func min(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?

Declared In

BidirectionalCollection, Collection, Sequence
func prefix(_:)

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero. Returns: A subsequence starting at the beginning of this collection with at most maxLength elements.

Declaration

func prefix(_ maxLength: Int) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func prefix(through:)

Returns a subsequence from the start of the collection through the specified position.

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection's subscript. The subscript notation is preferred over prefix(through:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"

end: The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property. Returns: A subsequence up to, and including, the end position.

Complexity: O(1)

Declaration

func prefix(through position: Self.Index) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func prefix(upTo:)

Returns a subsequence from the start of the collection up to, but not including, the specified position.

The resulting subsequence does not include the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, but not including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(upTo: i))
}
// Prints "[10, 20, 30]"

Passing the collection's starting index as the end parameter results in an empty subsequence.

print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[..<i])
}
// Prints "[10, 20, 30]"

end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection. Returns: A subsequence up to, but not including, the end position.

Complexity: O(1)

Declaration

func prefix(upTo end: Self.Index) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func prefix(while:)

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be included or false if it should be excluded. Once the predicate returns false it will not be called again.

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

Declaration

func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func randomElement()

Returns a random element of the collection.

Call randomElement() to select a random element from an array or another collection. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
// randomName == "Amani"

This method uses the default random generator, Random.default. The call to names.randomElement() above is equivalent to calling names.randomElement(using: &Random.default).

Returns: A random element from the collection. If the collection is empty, the method returns nil.

Declaration

func randomElement() -> Self.Element?

Declared In

BidirectionalCollection, Collection
func randomElement(using:)

Returns a random element of the collection, using the given generator as a source for randomness.

Call randomElement(using:) to select a random element from an array or another collection when you are using a custom random number generator. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement(using: &myGenerator)!
// randomName == "Amani"

generator: The random number generator to use when choosing a random element. Returns: A random element from the collection. If the collection is empty, the method returns nil.

Declaration

func randomElement<T>(using generator: inout T) -> Self.Element? where T : RandomNumberGenerator

Declared In

BidirectionalCollection, Collection
func reduce(_:_:)

Returns the result of combining the elements of the sequence using the given closure.

Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.

The nextPartialResult closure is called sequentially with an accumulating value initialized to initialResult and each element of the sequence. This example shows how to find the sum of an array of numbers.

let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
    x + y
})
// numberSum == 10

When numbers.reduce(_:_:) is called, the following steps occur:

  1. The nextPartialResult closure is called with initialResult---0 in this case---and the first element of numbers, returning the sum: 1.
  2. The closure is called again repeatedly with the previous call's return value and each element of the sequence.
  3. When the sequence is exhausted, the last value returned from the closure is returned to the caller.

If the sequence has no elements, nextPartialResult is never executed and initialResult is the result of the call to reduce(_:_:).

Parameters: initialResult: The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed. nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller. Returns: The final accumulated value. If the sequence has no elements, the result is initialResult.

Declaration

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result

Declared In

BidirectionalCollection, Collection, Sequence
func reduce(into:_:)

Returns the result of combining the elements of the sequence using the given closure.

Use the reduce(into:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies.

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

The updateAccumulatingResult closure is called sequentially with a mutable accumulating value initialized to initialResult and each element of the sequence. This example shows how to build a dictionary of letter frequencies of a string.

let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
    counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]

When letters.reduce(into:_:) is called, the following steps occur:

  1. The updateAccumulatingResult closure is called with the initial accumulating value---[:] in this case---and the first character of letters, modifying the accumulating value by setting 1 for the key "a".
  2. The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
  3. When the sequence is exhausted, the accumulating value is returned to the caller.

If the sequence has no elements, updateAccumulatingResult is never executed and initialResult is the result of the call to reduce(into:_:).

Parameters: initialResult: The value to use as the initial accumulating value. updateAccumulatingResult: A closure that updates the accumulating value with an element of the sequence. Returns: The final accumulated value. If the sequence has no elements, the result is initialResult.

Declaration

func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()) rethrows -> Result

Declared In

BidirectionalCollection, Collection, Sequence
func reversed()

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

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

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

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

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

Complexity: O(1)

Declaration

func reversed() -> ReversedCollection<Self>

Declared In

BidirectionalCollection, Collection, Sequence
func shuffled()

Returns the elements of the sequence, shuffled.

For example, you can shuffle the numbers between 0 and 9 by calling the shuffled() method on that range:

let numbers = 0...9
let shuffledNumbers = numbers.shuffled()
// shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]

This method uses the default random generator, Random.default. The call to numbers.shuffled() above is equivalent to calling numbers.shuffled(using: &Random.default).

Returns: A shuffled array of this sequence's elements.

Complexity: O(n)

Declaration

func shuffled() -> [Self.Element]

Declared In

BidirectionalCollection, Collection, Sequence
func shuffled(using:)

Returns the elements of the sequence, shuffled using the given generator as a source for randomness.

You use this method to randomize the elements of a sequence when you are using a custom random number generator. For example, you can shuffle the numbers between 0 and 9 by calling the shuffled(using:) method on that range:

let numbers = 0...9
let shuffledNumbers = numbers.shuffled(using: &myGenerator)
// shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]

generator: The random number generator to use when shuffling the sequence. Returns: An array of this sequence's elements in a shuffled order.

Complexity: O(n)

Declaration

func shuffled<T>(using generator: inout T) -> [Self.Element] where T : RandomNumberGenerator

Declared In

BidirectionalCollection, Collection, Sequence
func sorted(by:)

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

When you want to sort a sequence of elements that don't conform to the Comparable protocol, pass a predicate to this method that returns true when the first element passed should be ordered before the second. The elements of the resulting array are ordered according to the given predicate.

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areInIncreasingOrder(a, a) is always false. (Irreflexivity)
  • If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability)
  • Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability)

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements for which areInIncreasingOrder does not establish an order.

In the following example, the predicate provides an ordering for an array of a custom HTTPResponse type. The predicate orders errors before successes and sorts the error responses by their error code.

enum HTTPResponse {
    case ok
    case error(Int)
}

let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
let sortedResponses = responses.sorted {
    switch ($0, $1) {
    // Order errors by code
    case let (.error(aCode), .error(bCode)):
        return aCode < bCode

    // All successes are equivalent, so none is before any other
    case (.ok, .ok): return false

    // Order errors before successes
    case (.error, .ok): return true
    case (.ok, .error): return false
    }
}
print(sortedResponses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"

You also use this method to sort elements that conform to the Comparable protocol in descending order. To sort your sequence in descending order, pass the greater-than operator (>) as the areInIncreasingOrder parameter.

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Calling the related sorted() method is equivalent to calling this method and passing the less-than operator (<) as the predicate.

print(students.sorted())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
print(students.sorted(by: <))
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: A sorted array of the sequence's elements.

Declaration

func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element]

Declared In

BidirectionalCollection, Collection, Sequence
func split(_:omittingEmptySubsequences:whereSeparator:)

Returns the longest possible subsequences of the collection, in order, that don't contain elements satisfying the given predicate.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Parameters: maxSplits: The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the isSeparator predicate and for each element at the start or end of the collection satisfying the isSeparator predicate. The default value is true. isSeparator: A closure that takes an element as an argument and returns a Boolean value indicating whether the collection should be split at that element. Returns: An array of subsequences, split from this collection's elements.

Declaration

func split(maxSplits: Int = default, omittingEmptySubsequences: Bool = default, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]

Declared In

BidirectionalCollection, Collection
func starts(with:by:)

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.

The predicate must be a equivalence relation over the elements. That is, for any elements a, b, and c, the following conditions must hold:

  • areEquivalent(a, a) is always true. (Reflexivity)
  • areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry)
  • If areEquivalent(a, b) and areEquivalent(b, c) are both true, then areEquivalent(a, c) is also true. (Transitivity)

Parameters: possiblePrefix: A sequence to compare to this sequence. areEquivalent: A predicate that returns true if its two arguments are equivalent; otherwise, false. Returns: true if the initial elements of the sequence are equivalent to the elements of possiblePrefix; otherwise, false. If possiblePrefix has no elements, the return value is true.

Declaration

func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix, by areEquivalent: (Self.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool where PossiblePrefix : Sequence

Declared In

BidirectionalCollection, Collection, Sequence
func suffix(_:)

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

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero. Returns: A subsequence terminating at the end of the collection with at most maxLength elements.

Complexity: O(n), where n is equal to maxLength.

Declaration

func suffix(_ maxLength: Int) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection
func suffix(from:)

Returns a subsequence from the specified position to the end of the collection.

The following example searches for the index of the number 40 in an array of integers, and then prints the suffix of the array starting at that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.suffix(from: i))
}
// Prints "[40, 50, 60]"

Passing the collection's endIndex as the start parameter results in an empty subsequence.

print(numbers.suffix(from: numbers.endIndex))
// Prints "[]"

Using the suffix(from:) method is equivalent to using a partial range from the index as the collection's subscript. The subscript notation is preferred over suffix(from:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[i...])
}
// Prints "[40, 50, 60]"

start: The index at which to start the resulting subsequence. start must be a valid index of the collection. Returns: A subsequence starting at the start position.

Complexity: O(1)

Declaration

func suffix(from start: Self.Index) -> Self.SubSequence

Declared In

BidirectionalCollection, Collection

Where Element : Collection

func joined()

Returns the elements of this collection of collections, concatenated.

In this example, an array of three ranges is flattened so that the elements of each range can be iterated in turn.

let ranges = [0..<3, 8..<10, 15..<17]

// A for-in loop over 'ranges' accesses each range:
for range in ranges {
  print(range)
}
// Prints "0..<3"
// Prints "8..<10"
// Prints "15..<17"

// Use 'joined()' to access each element of each range:
for index in ranges.joined() {
    print(index, terminator: " ")
}
// Prints: "0 1 2 8 9 15 16"

Returns: A flattened view of the elements of this collection of collections.

Declaration

func joined() -> FlattenCollection<Self>

Declared In

BidirectionalCollection, Collection

Where Element : Comparable

func lexicographicallyPrecedes(_:)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.

This example uses the lexicographicallyPrecedes method to test which array of integers comes first in a lexicographical ordering.

let a = [1, 2, 2, 2]
let b = [1, 2, 3, 4]

print(a.lexicographicallyPrecedes(b))
// Prints "true"
print(b.lexicographicallyPrecedes(b))
// Prints "false"

other: A sequence to compare to this sequence. Returns: true if this sequence precedes other in a dictionary ordering; otherwise, false.

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use String APIs that perform localized comparison.

Declaration

func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence) -> Bool where OtherSequence : Sequence, Self.Element == OtherSequence.Element

Declared In

BidirectionalCollection, Collection, Sequence
@warn_unqualified_access func max()

Returns the maximum element in the sequence.

This example finds the largest value in an array of height measurements.

let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let greatestHeight = heights.max()
print(greatestHeight)
// Prints "Optional(67.5)"

Returns: The sequence's maximum element. If the sequence has no elements, returns nil.

Declaration

@warn_unqualified_access func max() -> Self.Element?

Declared In

BidirectionalCollection, Collection, Sequence
@warn_unqualified_access func min()

Returns the minimum element in the sequence.

This example finds the smallest value in an array of height measurements.

let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
let lowestHeight = heights.min()
print(lowestHeight)
// Prints "Optional(58.5)"

Returns: The sequence's minimum element. If the sequence has no elements, returns nil.

Declaration

@warn_unqualified_access func min() -> Self.Element?

Declared In

BidirectionalCollection, Collection, Sequence
func sorted()

Returns the elements of the sequence, sorted.

You can sort any sequence of elements that conform to the Comparable protocol by calling this method. Elements are sorted in ascending order.

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements that compare equal.

Here's an example of sorting a list of students' names. Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator (<).

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

To sort the elements of your sequence in descending order, pass the greater-than operator (>) to the sorted(by:) method.

let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Returns: A sorted array of the sequence's elements.

Declaration

func sorted() -> [Self.Element]

Declared In

BidirectionalCollection, Collection, Sequence

Where Element : Equatable

func contains(_:)

Returns a Boolean value indicating whether the sequence contains the given element.

This example checks to see whether a favorite actor is in an array storing a movie's cast.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
print(cast.contains("Marlon"))
// Prints "true"
print(cast.contains("James"))
// Prints "false"

element: The element to find in the sequence. Returns: true if the element was found in the sequence; otherwise, false.

Declaration

func contains(_ element: Self.Element) -> Bool

Declared In

BidirectionalCollection, Collection, Sequence
func elementsEqual(_:)

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

At least one of the sequences must be finite.

This example tests whether one countable range shares the same elements as another countable range and an array.

let a = 1...3
let b = 1...10

print(a.elementsEqual(b))
// Prints "false"
print(a.elementsEqual([1, 2, 3]))
// Prints "true"

other: A sequence to compare to this sequence. Returns: true if this sequence and other contain the same elements in the same order.

Declaration

func elementsEqual<OtherSequence>(_ other: OtherSequence) -> Bool where OtherSequence : Sequence, Self.Element == OtherSequence.Element

Declared In

BidirectionalCollection, Collection, Sequence
func firstIndex(of:)

Returns the first index where the specified value appears in the collection.

After using firstIndex(of:) to find the position of a particular element in a collection, you can use it to access the element by subscripting. This example shows how you can modify one of the names in an array of students.

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
    students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"

element: An element to search for in the collection. Returns: The first index where element is found. If element is not found in the collection, returns nil.

Declaration

func firstIndex(of element: Self.Element) -> Self.Index?

Declared In

BidirectionalCollection, Collection
func lastIndex(of:)

Returns the last index where the specified value appears in the collection.

After using lastIndex(of:) to find the position of the last instance of a particular element in a collection, you can use it to access the element by subscripting. This example shows how you can modify one of the names in an array of students.

var students = ["Ben", "Ivy", "Jordell", "Ben", "Maxime"]
if let i = students.lastIndex(of: "Ben") {
    students[i] = "Benjamin"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Benjamin", "Max"]"

element: An element to search for in the collection. Returns: The last index where element is found. If element is not found in the collection, returns nil.

Declaration

func lastIndex(of element: Self.Element) -> Self.Index?

Declared In

BidirectionalCollection
func split(_:maxSplits:omittingEmptySubsequences:)

Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the collection are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string at each space character (" "). The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(line.split(separator: " ", maxSplits: 1))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.split(separator: " ", omittingEmptySubsequences: false))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Parameters: separator: The element that should be split upon. maxSplits: The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each consecutive pair of separator elements in the collection and for each instance of separator at the start or end of the collection. If true, only nonempty subsequences are returned. The default value is true. Returns: An array of subsequences, split from this collection's elements.

Declaration

func split(separator: Self.Element, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [Self.SubSequence]

Declared In

BidirectionalCollection, Collection, Sequence
func starts(with:)

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

This example tests whether one countable range begins with the elements of another countable range.

let a = 1...3
let b = 1...10

print(b.starts(with: a))
// Prints "true"

Passing a sequence with no elements or an empty collection as possiblePrefix always results in true.

print(b.starts(with: []))
// Prints "true"

possiblePrefix: A sequence to compare to this sequence. Returns: true if the initial elements of the sequence are the same as the elements of possiblePrefix; otherwise, false. If possiblePrefix has no elements, the return value is true.

Declaration

func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix) -> Bool where PossiblePrefix : Sequence, Self.Element == PossiblePrefix.Element

Declared In

BidirectionalCollection, Collection, Sequence

Where Element : Sequence

func joined()

Returns the elements of this sequence of sequences, concatenated.

In this example, an array of three ranges is flattened so that the elements of each range can be iterated in turn.

let ranges = [0..<3, 8..<10, 15..<17]

// A for-in loop over 'ranges' accesses each range:
for range in ranges {
  print(range)
}
// Prints "0..<3"
// Prints "8..<10"
// Prints "15..<17"

// Use 'joined()' to access each element of each range:
for index in ranges.joined() {
    print(index, terminator: " ")
}
// Prints: "0 1 2 8 9 15 16"

Returns: A flattened view of the elements of this sequence of sequences.

Declaration

func joined() -> FlattenSequence<Self>

Declared In

BidirectionalCollection, Collection, Sequence
func joined(_:)

Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.

This example shows how an array of [Int] instances can be joined, using another [Int] instance as the separator:

let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let joined = nestedNumbers.joined(separator: [-1, -2])
print(Array(joined))
// Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"

separator: A sequence to insert between each of this sequence's elements. Returns: The joined sequence of elements.

Declaration

func joined<Separator>(separator: Separator) -> JoinedSequence<Self> where Separator : Sequence, Separator.Element == Self.Element.Element

Declared In

BidirectionalCollection, Collection, Sequence

Where Element : StringProtocol

func joined(_:)

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

The following example shows how an array of strings can be joined to a single, comma-separated string:

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let list = cast.joined(separator: ", ")
print(list)
// Prints "Vivien, Marlon, Kim, Karl"

separator: A string to insert between each of the elements in this sequence. The default separator is an empty string. Returns: A single, concatenated string.

Declaration

func joined(separator: String = default) -> String

Declared In

BidirectionalCollection, Collection, Sequence

Where Element == String

func joined(_:)

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

The following example shows how an array of strings can be joined to a single, comma-separated string:

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let list = cast.joined(separator: ", ")
print(list)
// Prints "Vivien, Marlon, Kim, Karl"

separator: A string to insert between each of the elements in this sequence. The default separator is an empty string. Returns: A single, concatenated string.

Declaration

func joined(separator: String = default) -> String

Declared In

BidirectionalCollection

Where ExtendedGraphemeClusterLiteralType == StringLiteralType

init(extendedGraphemeClusterLiteral:)

Creates an instance initialized to the given value.

value: The value of the new instance.

Declaration

init(extendedGraphemeClusterLiteral value: Self.StringLiteralType)

Declared In

ExpressibleByStringLiteral

Where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType

init(unicodeScalarLiteral:)

Creates an instance initialized to the given value.

value: The value of the new instance.

Declaration

init(unicodeScalarLiteral value: Self.ExtendedGraphemeClusterLiteralType)

Declared In

ExpressibleByStringLiteral , ExpressibleByExtendedGraphemeClusterLiteral

Where Indices == DefaultIndices

var indices: DefaultIndices<Self>

The indices that are valid for subscripting the collection, in ascending order.

A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead.

var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
    c[i] /= 5
    i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])

Declaration

var indices: DefaultIndices<Self> { get }

Declared In

BidirectionalCollection , Collection

Where Iterator == IndexingIterator

func makeIterator()

Returns an iterator over the elements of the collection.

Declaration

func makeIterator() -> IndexingIterator<Self>

Declared In

BidirectionalCollection, Collection

Where SubSequence == AnySequence

func drop(while:)

Returns a subsequence by skipping the initial, consecutive elements that satisfy the given predicate.

The following example uses the drop(while:) method to skip over the positive numbers at the beginning of the numbers array. The result begins with the first element of numbers that does not satisfy predicate.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let startingWithNegative = numbers.drop(while: { $0 > 0 })
// startingWithNegative == [-2, 9, -6, 10, 1]

If predicate matches every element in the sequence, the result is an empty sequence.

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result. Returns: A subsequence starting after the initial, consecutive elements that satisfy predicate.

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

Declaration

func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> AnySequence<Self.Element>

Declared In

BidirectionalCollection, Collection, Sequence
func dropFirst(_:)

Returns a subsequence containing all but the given number of initial elements.

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

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"

n: The number of elements to drop from the beginning of the sequence. n must be greater than or equal to zero. Returns: A subsequence starting after the specified number of elements.

Complexity: O(1).

Declaration

func dropFirst(_ n: Int) -> AnySequence<Self.Element>

Declared In

BidirectionalCollection, Collection, Sequence
func dropLast(_:)

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

The sequence must be finite. If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"

n: The number of elements to drop off the end of the sequence. n must be greater than or equal to zero. Returns: A subsequence leaving off the specified number of elements.

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

Declaration

func dropLast(_ n: Int) -> AnySequence<Self.Element>

Declared In

BidirectionalCollection, Collection, Sequence
func prefix(_:)

Returns a subsequence, up to the specified maximum length, containing the initial elements of the sequence.

If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero. Returns: A subsequence starting at the beginning of this sequence with at most maxLength elements.

Complexity: O(1)

Declaration

func prefix(_ maxLength: Int) -> AnySequence<Self.Element>

Declared In

BidirectionalCollection, Collection, Sequence
func prefix(while:)

Returns a subsequence containing the initial, consecutive elements that satisfy the given predicate.

The following example uses the prefix(while:) method to find the positive numbers at the beginning of the numbers array. Every element of numbers up to, but not including, the first negative value is included in the result.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let positivePrefix = numbers.prefix(while: { $0 > 0 })
// positivePrefix == [3, 7, 4]

If predicate matches every element in the sequence, the resulting sequence contains every element of the sequence.

predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result. Returns: A subsequence of the initial, consecutive elements that satisfy predicate.

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

Declaration

func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> AnySequence<Self.Element>

Declared In

BidirectionalCollection, Collection, Sequence
func split(_:omittingEmptySubsequences:whereSeparator:)

Returns the longest possible subsequences of the sequence, in order, that don't contain elements satisfying the given predicate. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " })
          .map(String.init))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(
   line.split(maxSplits: 1, whereSeparator: { $0 == " " })
                  .map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes true for the allowEmptySlices parameter, so the returned array contains empty strings where spaces were repeated.

print(
    line.split(
        omittingEmptySubsequences: false,
        whereSeparator: { $0 == " " }
    ).map(String.init))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Parameters: maxSplits: The maximum number of times to split the sequence, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original sequence containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the isSeparator predicate and for each element at the start or end of the sequence satisfying the isSeparator predicate. If true, only nonempty subsequences are returned. The default value is true. isSeparator: A closure that returns true if its argument should be used to split the sequence; otherwise, false. Returns: An array of subsequences, split from this sequence's elements.

Declaration

func split(maxSplits: Int = default, omittingEmptySubsequences: Bool = default, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [AnySequence<Self.Element>]

Declared In

BidirectionalCollection, Collection, Sequence
func suffix(_:)

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

The sequence must be finite. If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"

maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero. Complexity: O(n), where n is the length of the sequence.

Declaration

func suffix(_ maxLength: Int) -> AnySequence<Self.Element>

Declared In

BidirectionalCollection, Collection, Sequence

Where SubSequence == Slice

subscript(_: Range<Self.Index>)

Accesses a contiguous subrange of the collection's elements.

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

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

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

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// Prints "Evarts"

bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

subscript(bounds: Range<Self.Index>) -> Slice<Self> { get }

Declared In

BidirectionalCollection, Collection