Substring

struct Substring

A slice of a string.

Inheritance CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByStringLiteral, ExpressibleByUnicodeScalarLiteral, LosslessStringConvertible, RangeReplaceableCollection, StringProtocol, TextOutputStream, TextOutputStreamable
Associated Types
public typealias Index = String.Index

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.

public typealias SubSequence = Substring

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

Nested Types Substring.UTF8View, Substring.UTF16View, Substring.UnicodeScalarView

When you create a slice of a string, a Substring instance is the result. Operating on substrings is fast and efficient because a substring shares its storage with the original string. The Substring type presents the same interface as String, so you can avoid or defer any copying of the string's contents.

The following example creates a greeting string, and then finds the substring of the first sentence:

let greeting = "Hi there! It's nice to meet you! đź‘‹"
let endOfSentence = greeting.firstIndex(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"

You can perform many string operations on a substring. Here, we find the length of the first sentence and create an uppercase version.

print("'\(firstSentence)' is \(firstSentence.count) characters long.")
// Prints "'Hi there!' is 9 characters long."

let shoutingSentence = firstSentence.uppercased()
// shoutingSentence == "HI THERE!"

Converting a Substring to a String

This example defines a rawData string with some unstructured data, and then uses the string's prefix(while:) method to create a substring of the numeric prefix:

let rawInput = "126 a.b 22219 zzzzzz"
let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
// numericPrefix is the substring "126"

When you need to store a substring or pass it to a function that requires a String instance, you can convert it to a String by using the String(_:) initializer. Calling this initializer copies the contents of the substring to a new string.

func parseAndAddOne(_ s: String) -> Int {
    return Int(s, radix: 10)! + 1
}
_ = parseAndAddOne(numericPrefix)
// error: cannot convert value...
let incrementedPrefix = parseAndAddOne(String(numericPrefix))
// incrementedPrefix == 127

Alternatively, you can convert the function that takes a String to one that is generic over the StringProtocol protocol. The following code declares a generic version of the parseAndAddOne(_:) function:

func genericParseAndAddOne<S: StringProtocol>(_ s: S) -> Int {
    return Int(s, radix: 10)! + 1
}
let genericallyIncremented = genericParseAndAddOne(numericPrefix)
// genericallyIncremented == 127

You can call this generic function with an instance of either String or Substring.

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

Initializers

init init() Required

Creates an empty substring.

Declaration

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

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

Declaration

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

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

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

Declaration

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

Creates a Substring having the given content.

Complexity: O(1)

Declaration

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

Creates a Substring having the given content.

Complexity: O(1)

Declaration

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

Creates a Substring having the given content.

Complexity: O(1)

Declaration

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

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

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

Declaration

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

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

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

Declaration

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

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

Declaration

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

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

Declaration

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

Creates an instance initialized to the given value.

  • Parameter value: The value of the new instance.

Declaration

@inlinable public init(extendedGraphemeClusterLiteral value: String)
init init(repeating:count:) Required

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

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

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

Declaration

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

Creates a new instance from an interpolated string literal.

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

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

Declaration

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

Creates an instance initialized to the given string value.

  • Parameter value: The value of the new instance.

Declaration

@inlinable public init(stringLiteral value: String)
init init(unicodeScalarLiteral:) Required

Creates an instance initialized to the given value.

  • Parameter value: The value of the new instance.

Declaration

@inlinable public init(unicodeScalarLiteral value: String)

Instance Variables

var base Required

Returns the underlying string from which this Substring was derived.

Declaration

var base: String
var customMirror Required

The custom mirror for this instance.

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

Declaration

var customMirror: Mirror
var customPlaygroundQuickLook Required

A custom playground Quick Look for this instance.

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

Declaration

var customPlaygroundQuickLook: _PlaygroundQuickLook
var debugDescription Required

A textual representation of this instance, suitable for debugging.

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

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

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

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

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

Declaration

var debugDescription: String
var description 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
var endIndex Required

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

When you need a range that includes the last element of a collection, use the half-open range operator (..<) with endIndex. The ..< operator creates a range that doesn't include the upper bound, so it's always safe to use with endIndex. For example:

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

If the collection is empty, endIndex is equal to startIndex.

Declaration

var endIndex: Substring.Index
var isContiguousUTF8 Required

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

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

Declaration

var isContiguousUTF8: Bool
var startIndex Required

The position of the first element in a nonempty collection.

If the collection is empty, startIndex is equal to endIndex.

Declaration

var startIndex: Substring.Index
var unicodeScalars Required

Declaration

var unicodeScalars: Substring.UnicodeScalarView
var utf16 Required

Declaration

var utf16: Substring.UTF16View
var utf8 Required

Declaration

var utf8: Substring.UTF8View

Subscripts

subscript subscript(i:) Required

Accesses the element at the specified position.

The following example accesses an element of an array through its subscript to print its value:

var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
print(streets[1])
// Prints "Bryant"

You can subscript a collection with any valid index other than the collection's end index. The end index refers to the position one past the last element of a collection, so it doesn't correspond with an element.

  • Parameter position: The position of the element to access. position must be a valid index of the collection that is not equal to the endIndex property.

Complexity: O(1)

Declaration

public subscript(i: Substring.Index) -> Character
subscript subscript(r:) Required

Accesses a contiguous subrange of the collection's elements.

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

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

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

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

Complexity: O(1)

Declaration

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

Instance Methods

func append(_ newElement: Self.Element) Required

Adds an element to the end of the collection.

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

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

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

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

Declaration

@inlinable public mutating func append(_ newElement: Self.Element)
func append(contentsOf newElements: S) Required

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

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

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

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

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

Declaration

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

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

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

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

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

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

Declaration

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

Applies the given difference to this collection.

  • Parameter difference: The difference to be applied.

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

Declaration

@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func applying(_ difference: CollectionDifference<Self.Element>) -> Self?
func distance(from start: Substring.Index, to end: Substring.Index) -> Int Required

Returns the distance between two indices.

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

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

Declaration

@inlinable public func distance(from start: Substring.Index, to end: Substring.Index) -> Int
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> Self Required

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

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

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

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

Declaration

@available(swift 4.0) @inlinable public func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> Self
func filter(_ isIncluded: (Substring.Element) throws -> Bool) rethrows -> String Required

Declaration

public func filter(_ isIncluded: (Substring.Element) throws -> Bool) rethrows -> String
func hasPrefix(_ prefix: Prefix) -> Bool Required

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 extended grapheme clusters 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"
  • Parameter prefix: A possible prefix to test against this string.

Declaration

@inlinable public func hasPrefix<Prefix>(_ prefix: Prefix) -> Bool where Prefix: StringProtocol
func hasSuffix(_ suffix: Suffix) -> Bool Required

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 extended grapheme clusters 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"
  • Parameter suffix: A possible suffix to test against this string.

Declaration

@inlinable public func hasSuffix<Suffix>(_ suffix: Suffix) -> Bool where Suffix: StringProtocol
func hash(into hasher: inout Hasher) Required

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

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

Declaration

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

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

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

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

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

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

Declaration

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

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

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

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

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

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

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

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

Declaration

@inlinable public func index(_ i: Substring.Index, offsetBy n: Int, limitedBy limit: Substring.Index) -> Substring.Index?
func index(after i: Substring.Index) -> Substring.Index 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.

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

Declaration

@inlinable public func index(after i: Substring.Index) -> Substring.Index
func index(before i: Substring.Index) -> Substring.Index Required

Returns the position immediately before the given index.

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

Declaration

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

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

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

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

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

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

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

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

Declaration

@inlinable public mutating func insert(_ newElement: Self.Element, at i: Self.Index)
func insert(contentsOf newElements: C, at i: Self.Index) Required

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

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

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

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

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

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

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

Declaration

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

Declaration

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

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

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

Declaration

public mutating func makeContiguousUTF8()
func remove(at position: Self.Index) -> Self.Element Required

Removes and returns the element at the specified position.

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

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

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

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

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

Declaration

@inlinable public mutating func remove(at position: Self.Index) -> Self.Element
func removeAll(keepingCapacity keepCapacity: Bool = false) Required

Removes all elements from the collection.

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

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

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

Declaration

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

Removes all the elements that satisfy the given predicate.

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

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

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

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

Declaration

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

Removes and returns the first element of the collection.

The collection must not be empty.

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

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

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

Declaration

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

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

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

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

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

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

Declaration

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

Removes the elements in the specified subrange from the collection.

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

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

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

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

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

Declaration

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

Removes the elements in the specified subrange from the collection.

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

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

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

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

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

Declaration

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

Replaces the specified subrange of elements with the given collection.

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

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

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

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

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

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

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

Declaration

public mutating func replaceSubrange<C>(_ bounds: Range<Substring.Index>, with newElements: C) where C: Collection, C.Element == Substring.Iterator.Element
func replaceSubrange(_ bounds: Range<Substring.Index>, with newElements: Substring) Required

Declaration

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

Replaces the specified subrange of elements with the given collection.

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

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

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

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

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

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

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

Declaration

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

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

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

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

Declaration

@inlinable public mutating func reserveCapacity(_ n: Int)
func uppercased() -> String Required

Declaration

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

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

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

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

Declaration

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

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

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

Declaration

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

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

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

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

Declaration

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

Appends the given string to the stream.

Declaration

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

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

Declaration

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

Type Methods

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

Declaration

@inlinable public static func !=<RHS>(lhs: Self, rhs: RHS) -> Bool where RHS: StringProtocol
func +(lhs: Self, rhs: Other) -> Self Required

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

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

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

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

Declaration

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

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

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

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

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

Declaration

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

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

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

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

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

Declaration

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

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

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

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

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

Declaration

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

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

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

Declaration

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

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

Declaration

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

Returns a Boolean value indicating whether two values are equal.

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

Declaration

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

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

Declaration

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

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

Declaration

@inlinable public static func >=<RHS>(lhs: Self, rhs: RHS) -> Bool where RHS: StringProtocol