Bronze Challenge Solution

[edit]
Here is my solution to the Bronze Challenge. I’m leaving my comments in so that you guys can see my train of thought as I was figuring this out. I have to admit though, that I found the solution to the backspace/range.length issue on StackExchange.

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//        print("Current text: \(textField.text)")
//        print("Replacement text: \(string)")

        let existingTextHasDecimalSeparator = textField.text?.rangeOfString(".")
        let replacementTextHasDecimalSeparator = string.rangeOfString(".")

//        print("Range length: \(range.length)")

        if string.rangeOfCharacterFromSet(NSCharacterSet.init(charactersInString: ".0123456789")) != nil {
            // The input is defined in the character set
            if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
                return false
            } else {
                return true
            }
        } else {
            // The input is either something other than the defined character set

            // If the user hit backspace, range.length will == 1 because it will *change* 1 character
            if range.length == 1 {
                return true
            }

            return false
        }
    }

[/edit]

I’m slowly progressing, but my main challenge is getting around the concept of the String struct vs NSString. How is a String able to use the NSString methods?

When you say “how”, do you want to see the code that makes that possible, or do you just want to read that in fact you can do that?

If the latter, the topic is called “automatic bridging”, and here is one source that discusses it (start reading at the very top of the page):

books.google.com/books?id=ovmoC … rk&f=false

Note that when you import UIKit that also imports Foundation.

Thanks 7stud, that was the info I was looking for.

Luckily for me, I just happened to already solve the Challenge and I got on here to post my result. But it’s still good info to know.