The string cannot be indexed with int

I get an error in the last line when I try to set label1 to the first letter of string using the latest version of Swift. How to solve this problem?

 let preferences = UserDefaults.standard let name1 = "" + preferences.string(forKey: "name")! let name2 = name1 label1.text = name2.substring(from: 0) 
+7
ios swift3
source share
4 answers

This is because the substring method accepts String.Index instead of plain Int . Try instead:

 let index = name2.index(str.startIndex, offsetBy: 0) //replace 0 with index to start from label.text = name2.substring(from: index) 
+11
source share

first letter of a string in Swift 3

 label1.text = String(name2[name2.startIndex]) 

A string cannot be indexed by Int already in Swift 2

+1
source share

It queries the index, not Int.

 let str = "string" print(str.substring(from: str.startIndex)) 
0
source share

Here are a few features that make it more objective-c like

 func substringOfString(_ s: String, toIndex anIndex: Int) -> String { return s.substring(to: s.index(s.startIndex, offsetBy: anIndex)) } func substringOfString(_ s: String, fromIndex anIndex: Int) -> String { return s.substring(from: s.index(s.startIndex, offsetBy: anIndex)) } //examples let str = "Swift String implementation is completely and utterly irritating" let newstr = substringOfString(str, fromIndex: 30) // is completely and utterly irritating let anotherStr = substringOfString(str, toIndex: 14) // Swift String let thisString = substringOfString(anotherStr, toIndex: 5) // Swift 
0
source share

All Articles