Cannot call substringToIndex with int argument list type

I am trying to get this line to work:

textView.text = textView.text.substringToIndex(count(textView.text.utf16) - 1) 

error: Cannot call substringToIndex with int argument list type

+4
source share
4 answers

substringToIndex accepts a String.Index , which is different from Int. If you want to take a whole line minus the last character, you can do

 textView.text = textView.text.substringToIndex(advance(textView.text.endIndex, -1)) 
+5
source

To answer David, the problem mostly arose because of the differences between the Foundation NSString class and the Swift String .

The method is of type String needs <String.Index> because the handling of strings in Swift is different from the implementation of NSString .

To clarify, NSString instances do not use Unicode characters, while Swift needs a comprehensive approach to String regarding the use of Unicode characters. Therefore, you should be careful when dropping String to NSString s or vice versa.

+1
source

You can use this extension:

Swift 2.3

 extension String { func substringToIndex(index: Int) -> String { if (index < 0 || index > self.characters.count) { print("index \(index) out of bounds") return "" } return self.substringToIndex(self.startIndex.advancedBy(index)) } } 

Swift 3

 extension String { func substring(to index: Int) -> String { if (index < 0 || index > self.characters.count) { print("index \(index) out of bounds") return "" } return self.substring(to: self.characters.index(self.startIndex, offsetBy: index)) } } 

And use:

 textView.text = textView.text.substringToIndex(textView.text.characters.count - 1) 
+1
source

Use the code below for SWIFT 3: -

 if textView.text.characters.count > 100 { let tempStr = textView.text let index = tempStr?.index((tempStr?.endIndex)!, offsetBy: 100 - (tempStr?.characters.count)!) textView.text = tempStr?.substring(to: index!) } } 
0
source

All Articles