This is what I've been doing to change a single letter at a specific location in a word …
Where did you get that location? That is, in your example, where did the 1 come from?
The reason I ask is that numeric indexes like that rarely make sense in the general case of Unicode strings. For example, if you change the input of your original code to use a skin toned emoji, it’s results are less than ideal.
let word = "\u{1F466}\u{1F3FE}bc"
var letters = Array(word.characters)
letters[1] = "x"
let newWord = String(letters) // "\u{1F466}xbc"
What you do about this depends on the constraints that you can apply to your strings. For example, if you knew that
word
was ASCII (it’s a string from an HTTP header, say) then you can ignore Unicode and treat it like an array of
UInt8
. OTOH, if
word
is derived from user text, you’ll need to rethink your approach.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"