在Swift 3.0中循环遍历子串

时间:2017-03-08 03:13:50

标签: swift string loops substring swift-playground

在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

1 个答案:

答案 0 :(得分:2)

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)