How to increment a variable of type String.Charact

2020-06-23 06:13发布

问题:

I was trying this (at the Playground):

class SomeClass {

    private let input: String.CharacterView
    private var position: String.CharacterView.Index

    ...

    private func advance() {

        position += 1

    } // advance

} // SomeClass

...but I'm getting the following error message:

error: binary operator '+=' cannot be applied to operands of type 'String.CharacterView.Index' and 'Int'

The reason behind me trying to increment this index it's because I would like to do something like:

input[position]

...and access a specific character at input.

At this point I already know that I can't use this binary operator over position. What would be a viable solution?

I'm using Swift 3 and Xcode Version 8.0 beta 6 (8S201h)

回答1:

In Swift 3, "Collections move their index", compare A New Model for Collections and Indices on Swift evolution.

In your case

private func advance() {
    input.formIndex(&position, offsetBy: 1)
}

would advance the index position by one. Here you have to ensure that the index is not already equal to endIndex, alternatively use

private func advance() {
    input.formIndex(&position, offsetBy: 1, limitedBy: input.endIndex)
}


标签: swift swift3