title: Limit UITextField to one decimal point Swift
body: <p>How can I limit a UITextField to one decimal point with Swift? The text field is for entering a price, so I cannot allow more than one decimal point. If I was using Objective-C, I would have used this code:</p>
  
  <pre><code>-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
  {
      NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
  
      NSArray *sep = [newString componentsSeparatedByString:@"."];
      if([sep count] &gt;= 2)
      {
          NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
          return !([sepStr length]&gt;1);
      }
      return YES;
  }
  </code></pre>
  
  <p>But due a difference with how Swift uses ranges, I cannot convert this code to Swift. The first line gives me an error saying <code>NSRange is not convertible to Range&lt;String.Index&gt;</code></p>
  
  <p><strong>EDIT:</strong> I ended up doing it like this before I saw the answer:</p>
  
  <pre><code>func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -&gt; Bool {
      let tempRange = textField.text.rangeOfString(".", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil)
      if tempRange?.isEmpty == false &amp;&amp; string == "." {
          return false
      }
  
      return true
  }
  </code></pre>
  
  <p>I found this on a different post. This solution works fine but I'm not sure if it is the best way to do it but it is a short and clean way. </p>