Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Delegates in Swift 2 Delegation in iOS Modifying Behavior With Delegates

count the length of a String - Swift Delegate

Hi, in the video, count is done like this:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let length = count(textField.text) - range.length + count(string) // but this error occurred: "Cannot invoke 'count' with an argument list of type '(String?)'"
        if length > 0 {
            submitButton.enabled = true
        } else {
            submitButton.enabled = false
        return true

what I do?

2 Answers

Eduardo Pinheiro
Eduardo Pinheiro
4,649 Points

If you're using Xcode 7, you need to change 'count(textField.text)' to 'textField.text!.characters.count' and 'count(string)' to 'string.characters.count'.

gurminder thind
gurminder thind
Courses Plus Student 10,062 Points

Correct code for Xcode 8.1 is () func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let length = (textField.text?.characters.count)! - range.length + string.characters.count if length > 0 { submitButton.isEnabled = true } else { submitButton.isEnabled = false } return true } ()

Please note that count(textField.text) has been changed to (textField.text?.characters.count)! in Xcode 8.1 and also 'submitButton.enabled' has been changed to 'submitButton.isEnabled'. Again it will be nice if put in teacher's notes.