7

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)
Vadim
  • 9,383
  • 7
  • 36
  • 58
krikor Herlopian
  • 731
  • 1
  • 10
  • 23
  • 1
    See [How does String.Index work in Swift 3](http://stackoverflow.com/questions/39676939/how-does-string-index-work-in-swift-3) and [How does String substring work in Swift 3](http://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift-3) – Hamish Nov 09 '16 at 16:18

4 Answers4

11

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)
alexburtnik
  • 7,661
  • 4
  • 32
  • 70
1

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

vadian
  • 274,689
  • 30
  • 353
  • 361
0

It's asking for an Index, not an Int.

let str = "string"
print(str.substring(from: str.startIndex))
ohr
  • 1,717
  • 14
  • 15
0

Here's a couple of functions 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's 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's String
let thisString = substringOfString(anotherStr, toIndex: 5) // Swift
applehelpwriter
  • 488
  • 3
  • 8