Reputation: 731
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
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
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
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
Reputation: 1727
It's asking for an Index, not an Int.
let str = "string"
print(str.substring(from: str.startIndex))
Upvotes: 0