title: How to properly solve the EXC_BAD_ACCESS (code=EXC_i386_GPFLT) error in my function
body: <p>Ok, so total Swift noob here. Going through some beginner tutorials. </p>
  
  <p>In order to achieve some goal, </p>
  
  <blockquote>
    <p>I need a UITextField to accept only numbers</p>
  </blockquote>
  
  <p>I have managed to get the UITextField to accept only letters via this code:</p>
  
  <pre><code>import UIKit
  
  class ViewController: UIViewController, UITextFieldDelegate {
      @IBOutlet var TextField: UITextField!
      override func viewDidLoad() {
          super.viewDidLoad()
  
          self.TextField.delegate = self
      }
  
      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
  
          let allowedCharacters = CharacterSet.letters
          let characterSet = CharacterSet(charactersIn: string)
          return allowedCharacters.isSuperset(of: characterSet)
  
      }
  
  
  }
  </code></pre>
  
  <p>However as soon as I turn <code>allowedCharacters</code> into something like:</p>
  
  <p><code>let allowedCharacters = CharacterSet(charactersIn: "0123456789")</code></p>
  
  <p>The <code>Simulator</code> still launches successfully (and I get a <code>Build Succeeded</code> message)</p>
  
  <p>However, as soon as I start typing it crashes. Xcode then highlights my <code>return</code> statement and shows the error message:</p>
  
  <p><code>Thread 1: EXC_BAD_ACCESS (code=EXC_i386_GPFLT)</code> </p>
  
  <p>When I google for it I get the sense that it might have something to do with the fact that I might need to an <code>if-statement</code> somewhere in my function to catch any unexpected values that I guess are being returned as soon as I start typing in the textfield, but I can not see the logic yet as to where and how. </p>
  
  <p>Any thoughts to enlighten me would be great!  </p>
  
  <p><strong>PS</strong>: I know I could also just configure my textfield to only show a numpad, but I'd still like to know why the current solution is causing problems for I might need other, more advanced, restrictions sometime in the future.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Another solution that works (which I discovered after posting the question) is to change my declaration of allowedCharacters as such:</p>
  
  <p><code>let allowedCharacters = CharacterSet.decimalDigits</code></p>
  
  <p>However, the accepted answer to this question allows for more finetuning when necessary. </p>