在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
。
答案 0 :(得分:2)
start
和end
是String.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)