【问题标题】:looping through substrings in Swift 3.0在 Swift 3.0 中循环子串
【发布时间】:2017-03-08 03:13:50
【问题描述】:

在 Swift 3.0 中循环子字符串的最佳方法是什么?

var start = s.startIndex
var end = s.index(s.endIndex, offsetBy: -10)
   for i in start...end {


   }

以下代码抛出错误:Type ClosedRange<String.Index> (aka ‘ClosedRange<String.CharacterView.Index>’) does not conform to Sequence protocol

【问题讨论】:

    标签: swift string loops substring swift-playground


    【解决方案1】:

    startendString.Index的类型,不能在for循环中使用;相反,您可以在以下范围内获得substring

    var start = s.startIndex
    var end = s.index(s.endIndex, offsetBy: -10)
    let range = Range(uncheckedBounds: (lower: start, upper: end))
    let subString = s.substring(with: range)
    

    【讨论】:

      【解决方案2】:

      String.Index 不能用于 for 循环,但(子)字符串可以是 enumerated

      var start = s.startIndex
      var end = s.index(s.endIndex, offsetBy: -10)
      for (index, character) in s[start...end].enumerated() {
          print(index, character)
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-25
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多