2

When inspecting a text field by overriding the method below in swift:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool

the line below returns false when I type in a 1 into the text field

var hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (1 as unichar)

hasLeadingOne returns false but it should be true when I enter 1 into the text field. Moreover, the value of decimalString.characterAtIndex(0) seems to be 49 instead of 1 even when casted as unichar. What am I missing?

5
  • 3
    49 is the ASCII character code for 1. Commented Dec 10, 2015 at 16:30
  • And unichar is just a typealias for UInt16. The name unichar makes it sound like it is a character of some kind, but it is just a number. Commented Dec 10, 2015 at 16:33
  • 1
    so it should be true but it's still returning false Commented Dec 10, 2015 at 16:33
  • 1
    @Kenney More correctly, 49 is the Unicode value for the character 1. characterAtIndex: works in Unicode, not ASCII. Of course the first 127 ASCII is the same as the first 127 Unicode. Commented Dec 10, 2015 at 16:34
  • decimalString.characterAtIndex(0) == (49 as unichar) should be true, since 49 is the ASCII character code for 1, as @Kenney pointed out. Commented Dec 10, 2015 at 16:37

1 Answer 1

4

A suggestion... instead of using the complex boolean test that you've constructed, Swift offers an easy way to check if a String begins with a certain sequence of characters: hasPrefix. You can simplify your code like this:

var hasLeadingOne = decimalString.hasPrefix("1")

If you want to use the boolean test that you wrote, I believe that this will work:

var hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (49 as unichar)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.