[stdlib] Revise documentation for string-related types

This documentation revision covers a large number of types & protocols:
String, its views and their indices, the Unicode codec types and protocol,
as well as Character, UnicodeScalar, and StaticString, among others.

This also includes a few small changes across the standard library for
consistency.
This commit is contained in:
Nate Cook
2016-04-06 13:03:46 -05:00
parent 7f31d4e889
commit 44b2d56a7f
35 changed files with 2998 additions and 670 deletions

View File

@@ -14,18 +14,25 @@
// similar API.
extension String {
/// The index type for subscripting a string.
public typealias Index = CharacterView.Index
/// A type used to represent the number of steps between two `String.Index`
/// values, where one value is reachable from the other.
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
public typealias IndexDistance = CharacterView.IndexDistance
/// The position of the first `Character` in `self.characters` if
/// `self` is non-empty; identical to `endIndex` otherwise.
/// The position of the first character in a nonempty string.
///
/// In an empty string, `startIndex` is equal to `endIndex`.
public var startIndex: Index { return characters.startIndex }
/// The "past the end" position in `self.characters`.
/// A string's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
/// In an empty string, `endIndex` is equal to `startIndex`.
public var endIndex: Index { return characters.endIndex }
// TODO: swift-3-indexing-model - add docs
@@ -55,16 +62,25 @@ extension String {
return characters.distance(from: start, to: end)
}
/// Access the `Character` at `position`.
/// Accesses the character at the given position.
///
/// - Precondition: `position` is a valid position in `self.characters`
/// and `position != endIndex`.
/// Indices for a subscripting a string are shared with the string's
/// `characters` view. For example:
///
/// let greeting = "Hello, friend!"
/// if let i = greeting.characters.index(where: { $0 >= "A" && $0 <= "Z" }) {
/// print("First capital letter: \(greeting[i])")
/// }
/// // Prints "First capital letter: H"
///
/// - Parameter i: A valid index of the string. `i` must be less than the
/// string's end index.
public subscript(i: Index) -> Character { return characters[i] }
/// Return the characters within the given `bounds`.
/// Accesses the text in the given range.
///
/// - Complexity: O(1) unless bridging from Objective-C requires an
/// O(N) conversion.
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
public subscript(bounds: Range<Index>) -> String {
return String(characters[bounds])
}
@@ -79,24 +95,63 @@ public func < (lhs: String.Index, rhs: String.Index) -> Bool {
}
extension String {
/// Create an instance containing `characters`.
/// Creates a new string containing the characters in the given sequence.
///
/// You can use this initializer to create a new string from the result of
/// one or more operations on a string's `characters` view. For example:
///
/// let str = "The rain in Spain stays mainly in the plain."
///
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// let disemvowelled = String(str.characters.lazy.filter { !vowels.contains($0) })
///
/// print(disemvowelled)
/// // Prints "Th rn n Spn stys mnly n th pln."
///
/// - Parameter characters: A sequence of characters.
public init<
S : Sequence where S.Iterator.Element == Character
>(_ characters: S) {
self._core = CharacterView(characters)._core
}
/// Reserves enough space in the string's underlying storage to store the
/// specified number of ASCII characters.
///
/// Because each character in a string can require more than a single ASCII
/// character's worth of storage, additional allocation may be necessary
/// when adding characters to a string after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*)
public mutating func reserveCapacity(_ n: Int) {
withMutableCharacters {
(v: inout CharacterView) in v.reserveCapacity(n)
}
}
/// Appends the given character to the string.
///
/// The following example adds an emoji globe to the end of a string.
///
/// var globe = "Globe "
/// globe.append("🌍")
/// print(globe)
/// // Prints "Globe 🌍"
///
/// - Parameter c: The character to append to the string.
public mutating func append(_ c: Character) {
withMutableCharacters {
(v: inout CharacterView) in v.append(c)
}
}
/// Appends the characters in the given sequence to the string.
///
/// - Parameter newElements: A sequence of characters.
public mutating func append<
S : Sequence where S.Iterator.Element == Character
>(contentsOf newElements: S) {
@@ -106,13 +161,20 @@ extension String {
}
% for Range in ['Range', 'ClosedRange']:
/// Replace the characters within `bounds` with the elements of
/// `replacement`.
/// Replaces the text within the specified bounds with the given characters.
///
/// Invalidates all indices with respect to `self`.
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Complexity: O(`bounds.count`) if `bounds.upperBound
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
/// - Parameters:
/// - bounds: The range of text to replace. The bounds of the range must be
/// valid indices of the string.
/// - newElements: The new characters to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the string and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes text at the end of the string, the complexity is O(*n*), where
/// *n* is equal to `bounds.count`.
public mutating func replaceSubrange<
C : Collection where C.Iterator.Element == Character
>(
@@ -125,12 +187,20 @@ extension String {
}
}
/// Replace the text in `bounds` with `replacement`.
/// Replaces the text within the specified bounds with the given string.
///
/// Invalidates all indices with respect to `self`.
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Complexity: O(`bounds.count`) if `bounds.upperBound
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
/// - Parameters:
/// - bounds: The range of text to replace. The bounds of the range must be
/// valid indices of the string.
/// - newElements: The new text to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the string and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes text at the end of the string, the complexity is O(*n*), where
/// *n* is equal to `bounds.count`.
public mutating func replaceSubrange(
_ bounds: ${Range}<Index>, with newElements: String
) {
@@ -139,22 +209,37 @@ extension String {
}
% end
/// Insert `newElement` at position `i`.
/// Inserts a new character at the specified position.
///
/// Invalidates all indices with respect to `self`.
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Complexity: O(`self.count`).
/// - Parameters:
/// - newElement: The new character to insert into the string.
/// - i: A valid index of the string. If `i` is equal to the string's end
/// index, this methods appends `newElement` to the string.
///
/// - Complexity: O(*n*), where *n* is the length of the string.
public mutating func insert(_ newElement: Character, at i: Index) {
withMutableCharacters {
(v: inout CharacterView) in v.insert(newElement, at: i)
}
}
/// Insert `newElements` at position `i`.
/// Inserts a collection of characters at the specified position.
///
/// Invalidates all indices with respect to `self`.
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Complexity: O(`self.count + newElements.count`).
/// - Parameters:
/// - newElements: A collection of `Character` elements to insert into the
/// string.
/// - i: A valid index of the string. If `i` is equal to the string's end
/// index, this methods appends the contents of `newElements` to the
/// string.
///
/// - Complexity: O(*n*), where *n* is the combined length of the string and
/// `newElements`.
public mutating func insert<
S : Collection where S.Iterator.Element == Character
>(contentsOf newElements: S, at i: Index) {
@@ -163,11 +248,24 @@ extension String {
}
}
/// Remove and return the `Character` at position `i`.
/// Removes and returns the character at the specified position.
///
/// Invalidates all indices with respect to `self`.
/// All the elements following `i` are moved to close the gap. This example
/// removes the hyphen from the middle of a string.
///
/// - Complexity: O(`self.count`).
/// var nonempty = "non-empty"
/// if let i = nonempty.characters.index(of: "-") {
/// nonempty.remove(at: i)
/// }
/// print(nonempty)
/// // Prints "nonempty"
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameter i: The position of the character to remove. `i` must be a
/// valid index of the string that is not equal to the string's end index.
/// - Returns: The character that was removed.
@discardableResult
public mutating func remove(at i: Index) -> Character {
return withMutableCharacters {
@@ -176,11 +274,19 @@ extension String {
}
% for Range in ['Range', 'ClosedRange']:
/// Remove the characters in `bounds`.
/// Removes the characters in the given range.
///
/// Invalidates all indices with respect to `self`.
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Complexity: O(`self.count`).
% if Range == 'ClosedRange':
/// - Parameter bounds: The range of the elements to remove. The upper and
/// lower bounds of `bounds` must be valid indices of the string and not
/// equal to the string's end index.
% else:
/// - Parameter bounds: The range of the elements to remove. The upper and
/// lower bounds of `bounds` must be valid indices of the string.
% end
public mutating func removeSubrange(_ bounds: ${Range}<Index>) {
// FIXME: swift-3-indexing-model: tests.
withMutableCharacters {
@@ -189,13 +295,15 @@ extension String {
}
% end
/// Replace `self` with the empty string.
/// Replaces this string with the empty string.
///
/// Invalidates all indices with respect to `self`.
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - parameter keepCapacity: If `true`, prevents the release of
/// allocated storage, which can be a useful optimization
/// when `self` is going to be grown again.
/// - Parameter keepCapacity: Pass `true` to prevent the release of the
/// string's allocated storage. Retaining the storage can be a useful
/// optimization when you're planning to grow the string again. The
/// default value is `false`.
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
withMutableCharacters {
(v: inout CharacterView) in v.removeAll(keepingCapacity: keepCapacity)