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)
1

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.