error fatal: no se puede incrementar endIndex

Por alguna razón me sale

error fatal: no se puede incrementar endIndex

en la línea myRange. ¿Por qué recibo este error? No entiendo qué está mal con mi código.

import UIKit class ViewController: UIViewController { @IBOutlet var drag: UIPanGestureRecognizer! @IBOutlet weak var currentLabel: UILabel! @IBOutlet weak var label1: UILabel! @IBOutlet weak var label2: UILabel! @IBOutlet weak var label3: UILabel! @IBOutlet weak var label4: UILabel! @IBOutlet weak var label5: UILabel! @IBOutlet weak var label6: UILabel! @IBOutlet weak var label7: UILabel! @IBOutlet weak var label8: UILabel! @IBOutlet weak var label9: UILabel! let letter = "OX" var currentLetter = Character!() var decide = 0 var labelArray = [UILabel]() var moveCounter = 0 override func viewDidLoad() { super.viewDidLoad() getCurrentLetter() labelArray = [label1,label2,label3,label4,label5,label6,label7,label8,label9] } func getCurrentLetter() { let myRange = Range<String.Index>(start: letter.startIndex.advancedBy(decide), end: letter.startIndex.advancedBy(decide+1)) currentLabel.text = letter.substringWithRange(myRange) currentLetter = Character(letter.substringWithRange(myRange)) } func reset() { decide = 0 } @IBAction func dragObject(sender: UIPanGestureRecognizer) { let points = sender.locationInView(view) let currentPoints = currentLabel.frame.origin currentLabel.center = CGPointMake(points.x, points.y) for item in labelArray { if CGRectContainsPoint(item.frame, points) { item.text = String(currentLetter) decide++ drag.enabled = false currentLabel.center = currentPoints } else if drag.enabled == false { decide++ drag.enabled = true currentLabel.center = currentPoints } if decide == 2 { reset() } getCurrentLetter() } } } 

Su problema es que decide o decide+1 es más largo que la cadena. Afortunadamente, hay un código incorporado para solucionar esto.

Intenta replace

 let myRange = Range<String.Index>(start: letter.startIndex.advancedBy(decide), end: letter.startIndex.advancedBy(decide+1)) currentLabel.text = letter.substringWithRange(myRange) currentLetter = Character(letter.substringWithRange(myRange)) 

con

 let end = letter.endIndex.advancedBy(-1, limit: letter.startIndex) //The -1 is actually requinetworking, as the 'limit:' bit does <=, not just < let pos = letter.startIndex.advancedBy(decide, limit: end) currentLetter = letter[pos] currentLabel.text = currentLetter 
    Intereting Posts