krikor Herlopian
krikor Herlopian

Reputation: 731

String may not be indexed with int

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)

Upvotes: 7

Views: 2918

Answers (4)

applehelpwriter
applehelpwriter

Reputation: 488

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

Upvotes: 0

alexburtnik
alexburtnik

Reputation: 7741

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)

Upvotes: 11

vadian
vadian

Reputation: 285072

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

Upvotes: 1

ohr
ohr

Reputation: 1727

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

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

Upvotes: 0

Related Questions