在swift编程语言书中,它指出
You can use the startIndex and endIndex properties and the index(before:), index(after:), and index(_:offsetBy:) methods on any type that conforms to the Collection protocol. This includes String, as shown here, as well as collection types such as Array, Dictionary, and Set.
但是我查看了swift的string api的apple文档,并没有说明String
类型符合Collection
协议(protocol)
我一定是在这里遗漏了一些东西,但似乎无法弄清楚。
最佳答案
从 Swift 2 开始,String
不符合 Collection
,只是它的各种“ View ”
像 characters
、utf8
、utf16
或 unicodeScalars
。
(这可能在未来再次改变,比较 String should be a Collection of Characters Again在 String Processing For Swift 4 .)
它有 startIndex
和 endIndex
属性和 index
方法,这些
被转发到 characters
View ,如在
源代码
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)
}
// ...
}
关于ios - swift 的字符串类型是否符合集合协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43061572/