Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Value of type 'string' has no member 'length' [closed]

Tags:

string

ios

swift

I Have Implement Some TextField Functionalities in my App so I used TextField Delegates but it show some error like "Value of type string has no member length" I don't know how to solve this please help me for fix this issue.

Here I Give the Code of What I am trying.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    var oldLength: Int = textField.text!.characters.count
    var replacementLength: Int = string.characters.count
    var rangeLength: Int = range.length
    var newLength: Int = oldLength - rangeLength + replacementLength
    if textField.tag == 1 {
        if string.length > 0 && !NSScanner.scannerWithString(string).scanInt(nil) {  **------>//Error was showed in this line.**
            return false
        }
        // This 'tabs' to next field when entering digits
        if newLength == 5 {
            if textField == txtOtp4 {
                textField.resignFirstResponder()
            }
        }
        else if oldLength > 0 && newLength == 0 {

        }

        return newLength <= 4
    }
    else {
        if newLength == 11 {
            if textField == txtPhoneNumber {
                textField.resignFirstResponder()
            }
            return newLength <= 10
        }
    }
    return true
    // This allows numeric text only, but also backspace for deletes
}
like image 618
B.Saravana Kumar Avatar asked Feb 25 '16 09:02

B.Saravana Kumar


2 Answers

Replace

if string.length > 0

by

if string.characters.count > 0

Edit for Swift 4:

String now conforms to the Collection protocol, so it has a count property.

like image 50
Tim Vermeulen Avatar answered Oct 22 '22 10:10

Tim Vermeulen


If you're using Swift 2.0, you should use

string.characters.count

to get the number of characters in the String.

like image 8
mohonish Avatar answered Oct 22 '22 11:10

mohonish