title: Formatting Phone number in Swift
body: <p>I'm formatting my textfiled text once the user start typing the phone number into this format type <code>0 (555) 444 66 77</code> and it is working fine but once I get the number from the server I get it like this <code>05554446677</code> So please could you tell me how I can edit it in the same format once I get it fro the server?</p>
  
  <p>My code once I start typing:</p>
  
  <pre><code>func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -&gt; Bool {
  
      if textField == phoneNumberTextField{
          var newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
          var components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
  
          var decimalString = "".join(components) as NSString
          var length = decimalString.length
          var hasLeadingOne = length &gt; 0 &amp;&amp; decimalString.characterAtIndex(0) == (1 as unichar)
  
          if length == 0 || (length &gt; 11 &amp;&amp; !hasLeadingOne) || length &gt; 12{
              var newLength = (textField.text as NSString).length + (string as NSString).length - range.length as Int
  
              return (newLength &gt; 11) ? false : true
          }
          var index = 0 as Int
          var formattedString = NSMutableString()
  
          if hasLeadingOne{
              formattedString.appendString("1 ")
              index += 1
          }
  
          if (length - index) &gt; 1{
              var zeroNumber = decimalString.substringWithRange(NSMakeRange(index, 1))
              formattedString.appendFormat("%@ ", zeroNumber)
              index += 1
          }
          if (length - index) &gt; 3{
              var areaCode = decimalString.substringWithRange(NSMakeRange(index, 3))
              formattedString.appendFormat("(%@) ", areaCode)
              index += 3
          }
          if (length - index) &gt; 3{
              var prefix = decimalString.substringWithRange(NSMakeRange(index, 3))
              formattedString.appendFormat("%@ ", prefix)
              index += 3
          }
          if (length - index) &gt; 3{
              var prefix = decimalString.substringWithRange(NSMakeRange(index, 2))
              formattedString.appendFormat("%@ ", prefix)
              index += 2
          }
  
          var remainder = decimalString.substringFromIndex(index)
          formattedString.appendString(remainder)
          textField.text = formattedString as String
          return false
      }else{
          return true
      }
  }
  </code></pre>