在swift编程语言书中,它说明了
您可以使用startIndex和endIndex属性和 索引(前:),索引(后:)和索引(_:offsetBy :)上的方法 符合Collection协议的类型。这包括String, 如此处所示,以及集合类型,如Array,Dictionary, 和Set。
但是,我已经检查了swift的字符串api上的apple文档,这并不表示String
类型符合Collection
协议
我必须在这里遗漏一些东西,但似乎无法弄明白。
答案 0 :(得分:3)
从Swift 2开始,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)
}
// ...
}