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)
}
// ...
}
2条答案
按热度按时间vngu2lb81#
从SWIFT 2开始,
String
不符合Collection
,只符合characters
、utf8
、utf16
或unicodeScalars
等各种“视图”。(这在将来可能会再次更改,比较字符串应该再次是String Processing For Swift 4中的字符集合。)
它具有
startIndex
和endIndex
属性以及index
方法,但是这些属性被转发到characters
视图,如源代码StringRangeReplaceableCollection.swft.gyb所示:egdjgwm82#
字符串又是集合。这意味着您可以反转它们、逐个字符地循环它们、map()和flatMap()等等。例如:
让我们引用=“新的SWIFT版本带来了新的功能,这是举世公认的事实。”Let Reverted=Quote.Reverted()
对于引用中的Letter{print(Letter)},这一更改是作为称为字符串宣言的广泛修订的一部分引入的。