【问题标题】:does swift's string type conform to collection protocol?swift 的字符串类型是否符合收集协议?
【发布时间】:2017-03-28 05:53:21
【问题描述】:

在 swift 编程语言书中,它指出

您可以使用 startIndex 和 endIndex 属性以及 index(before:)、index(after:) 和 index(_:offsetBy:) 方法 符合 Collection 协议的类型。这包括字符串, 如此处所示,以及集合类型如 Array、Dictionary、 和设置。

不过,我查过苹果关于swift的string api的文档,并不表示String类型符合Collection协议

我一定在这里遗漏了一些东西,但似乎无法弄清楚。

【问题讨论】:

    标签: ios swift string collections protocols


    【解决方案1】:

    截至 Swift 2,String 不符合 Collection,只有它的各种“视图” 比如charactersutf8utf16unicodeScalars

    (这可能会在未来再次改变,比较 String should be a Collection of Characters AgainString Processing For Swift 4.)

    虽然它有 startIndexendIndex 属性和 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)
      }
    
    
      // ...
    }
    

    【讨论】:

    • 嗨,马丁!很高兴再次见到你,希望你今天过得愉快:)
    • 你的回答让我惊喜不断!它是如此完整和知情!你介意我问你用什么方法来寻找资源和解决问题吗?因为如果我一个人,我需要几天时间才能找到这些相关资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2016-07-02
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多