Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fatal error: can not increment endIndex

For some reason I get

fatal error: can not increment endIndex

at line myRange. Why I am getting this error? I don't understand whats wrong with my code.

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()
      }
   }
}
like image 580
123558 Avatar asked Feb 16 '16 05:02

123558


Video Answer


1 Answers

Your problem is that either decide or decide+1 is longer than the string is. Thankfully, there is some built in code to fix this.

Try replacing

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))

with

let end = letter.endIndex.advancedBy(-1, limit: letter.startIndex) //The -1 is actually required, as the 'limit:' bit does <=, not just <
let pos = letter.startIndex.advancedBy(decide, limit: end)
currentLetter = letter[pos]
currentLabel.text = currentLetter
like image 153
thislooksfun Avatar answered Sep 18 '22 23:09

thislooksfun