Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String may not be indexed with int

Tags:

ios

swift3

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

let preferences = UserDefaults.standard
let name1 = "" + preferences.string(forKey: "name")!
let name2 = name1
label1.text = name2.substring(from: 0)
like image 717
krikor Herlopian Avatar asked Nov 09 '16 16:11

krikor Herlopian


2 Answers

That's because substring method accepts String.Index instead of plain Int. Try this instead:

let index = name2.index(str.startIndex, offsetBy: 0) //replace 0 with index to start from
label.text = name2.substring(from: index)
like image 109
alexburtnik Avatar answered Nov 13 '22 12:11

alexburtnik


the first letter of the string in Swift 3 is

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

String could not be indexed by Int already in Swift 2

like image 26
vadian Avatar answered Nov 13 '22 10:11

vadian