Hi,
I was trying to use the insert method to insert a character at a particular location in string , but cannot seem to do so , below is my code , where am I wrong kindly guide
var greeting = "Guten Tang!"
let index = greeting.index(greeting.startIndex, offsetBy: 2)
greeting.insert("a", at: greeting[index])
Thanks
Amit Shrivastava
Make sure you read error messages and think about what they might mean. Sometimes Swift's error messages can be pretty bad (especially if your code involves a lot of closures or functions with multiple overloads), but in this case they're definitely useful:
error: repl.swift:5:34: error: cannot convert value of type 'Character' to expected argument type 'String.Index'
greeting.insert("a", at: greeting[index])
~~~~~~~~^~~~~~~
Here, the compiler is saying that it's trying to take a value of type Character
, and use it in a place that expects a String.Index
. The fancy ~~~
thingy is pointing at greeting[index]
indicating that this is the position the compiler thinks the error occurred. This makes sense, since greeting[index]
is indeed a Character
(specifically the character "t"
). According to the compiler, the function we're calling wanted a String.Index
rather than a Character
. Can you think of a value you've calculated that has the type String.Index
?
5 Likes
Oh thanks I got it now , I need to use
greeting.insert("a", at: index)
1 Like