Swift 3.0 iterate over String.Index range

后端 未结 9 1305
温柔的废话
温柔的废话 2020-12-16 10:27

The following was possible with Swift 2.2:

let m = \"alpha\"
for i in m.startIndex..

With 3.0,

9条回答
  •  暖寄归人
    2020-12-16 11:03

    To concretely demonstrate how to traverse through a range in a string in Swift 4, we can use the where filter in a for loop to filter its execution to the specified range:

    func iterateStringByRange(_ sentence: String, from: Int, to: Int) {
    
        let startIndex = sentence.index(sentence.startIndex, offsetBy: from)
        let endIndex = sentence.index(sentence.startIndex, offsetBy: to)
    
        for position in sentence.indices where (position >= startIndex && position < endIndex) {
            let char = sentence[position]
            print(char)
        }
    
    }
    

    iterateStringByRange("string", from: 1, to: 3) will print t, r and i

提交回复
热议问题