2

Here is my code:

var myString:String = "abc"

var myStringArray = Array(myString)

myStringArray[0] = String("cow")

I turn the string "abc" into the array ["a","b","c"]. I then try to turn the first element into "cow" so that I have the array ["cow","b","c"]. But it doesn't let me do the last part (i.e. the third line) since the elements in the array are CHARACTERS not STRINGS (so I can't replace the character "a" with the string "cow").

So how do I overcome this? I assume I want to make it so the elements in ["a","b","c"] are interpreted in the program as strings (that are each one letter long), so that I can make the desired replacement. But how to do that?

2 Answers 2

5

You can use your new array's map method to convert the Character instances to String:

var myString:String = "abc"

var myStringArray = Array(myString).map { String($0) }

myStringArray[0] = String("cow")
Sign up to request clarification or add additional context in comments.

Comments

2
var myString:String = "abc"

var myStringArray = myString.characters.map{String($0)}

myStringArray[0] = String("cow")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.