Swift: Value of type 'string' has no member 'length'
12,688
Solution 1
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.
Solution 2
If you're using Swift 2.0, you should use
string.characters.count
to get the number of characters in the String.
Author by
B.Saravana Kumar
Updated on June 13, 2022Comments
-
B.Saravana Kumar almost 2 years
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 }