title: Swift - Textview Identify Tapped Word Not Working
body: <p>Long time user, first time poster, so my apologies if I make any errors in presenting my question. I have been working on this for hours and I've decided it is time to ask the experts. I have also searched through every similar question that has been "answered" and work, which leads me to believe they are outdated.</p>
  
  <p>I am attempting to grab the tapped word from a UITextview that would be used later in the code. For example, there is a paragraph of words in the text view:</p>
  
  <p>"The initial return on time investment is much smaller, due to him trading his upfront cost for sweat-equity in the company, but the potential long-term payout is much greater". </p>
  
  <p>I would want to be able to tap on a word, e.g. 'investment', and run it through another function to define it. However simply tapping the word, crashes the program, and I do not receive the word tapped.</p>
  
  <p>I implemented a tap gesture recognizer:</p>
  
  <pre><code>let tap = UITapGestureRecognizer(target: self, action: #selector(tapResponse(_:)))
      tap.delegate = self
      tvEditor.addGestureRecognizer(tap)
  </code></pre>
  
  <p>and then wrote the function: <a href="http://i.stack.imgur.com/t1ViU.png" rel="nofollow">2</a></p>
  
  <pre><code>func tapResponse(recognizer: UITapGestureRecognizer) {
      let location: CGPoint = recognizer.locationInView(tvEditor)
      let position: CGPoint = CGPointMake(location.x, location.y)
      let tapPosition: UITextPosition = tvEditor.closestPositionToPoint(position)!
      let textRange: UITextRange = tvEditor.tokenizer.rangeEnclosingPosition(tapPosition, withGranularity: UITextGranularity.Word, inDirection: 1)!
  
      let tappedWord: String = tvEditor.textInRange(textRange)!
      print("tapped word : %@", tappedWord)
  }
  </code></pre>
  
  <p>Ideally, this should take the <strong>location</strong> from the tapped part of the Textview, take the <strong>position</strong> by taking the .x &amp; .y, and then looking through the Textview at the point closest to the <strong>position</strong>, finding the <strong>Range</strong> enclosing the position with granularity (to return the word), and setting the contents as a String, which I am currently just printing to the console. However, on tapping the word, I receive this crash.<a href="http://i.stack.imgur.com/6LKqE.png" rel="nofollow">3</a> </p>
  
  <p>along with "<strong>fatal error: unexpectedly found nil while unwrapping an Optional value"</strong> in the console.</p>
  
  <p>Any help would be greatly appreciated. I may just be missing something simple, or it could be much more complicated.</p>