2017-03-08 53 views
0

在Swift 3.0中循環一個子字符串的最佳方法是什麼?在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

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)