String
不符合Collection
,只有它的各种“视图”,如characters
、utf8
、utf16
或unicodeScalars
。
(这可能会在未来再次改变,请参见String should be a Collection of Characters Again in String Processing For Swift 4。)
它具有startIndex
和endIndex
属性以及index
方法,但是这些都被转发到characters
视图中,可以在源代码StringRangeReplaceableCollection.swift.gyb中看到:
extension String {
/// The index type for subscripting a string.
public typealias Index = CharacterView.Index
// ...
/// 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 }
/// A string's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// In an empty string, `endIndex` is equal to `startIndex`.
public var endIndex: Index { return characters.endIndex }
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Index) -> Index {
return characters.index(after: i)
}
// ...
}
字符串是一组字符的集合。这意味着您可以对它们进行反转,逐个字符地循环遍历、映射(map())和扁平化(flatMap())等操作。例如:
let quote = "It is a truth universally acknowledged that new Swift versions bring new features." let reversed = quote.reversed()
for letter in quote { print(letter) } 这个变化是作为一个广泛的修改集合——字符串宣言的一部分引入的。