+ 8

Why am I getting an error appending a string to a string array?

I am trying to append a string to a string array, but I get an error saying it must be a substring. The documentation says you can do it? So I must be confused such that what I understand it to say is not what it is saying. let name = readLine()! + "z" var customers = readLine()!.split(separator: " ") customers.append(name)

25th Apr 2020, 1:58 AM
Paul K Sadler
Paul K Sadler - avatar
3 Answers
+ 3
You can't append a string to an array whether it may be string array. You can append a string to a string only and if you want to add something to a string array then just in some variable store the last index of the string array where you had added something and with the help of that variable store your string at the next index in the string array
25th Apr 2020, 2:31 AM
Prabhat Ranjan
Prabhat Ranjan - avatar
+ 1
Prabhat Ranjan thank you for your response. I pulled this right out of the apple doc: students.append("Maxime") students.append(contentsOf: ["Shakia", "William"]) // ["Ben", "Ivy", "Jordell", "Maxime", "Shakia", "William"] It seems to indicate that you can do it in Swift 4 (SO too has many examples). Clearly I am missing something. Could I trouble you to expound further?
25th Apr 2020, 2:43 AM
Paul K Sadler
Paul K Sadler - avatar
+ 1
Prabhat Ranjan what you said did help me work around the issue for now: var customers = (readLine()! + " " + name).split(separator: " ") Effectively, I appended name to the customers array 🙃
25th Apr 2020, 2:52 AM
Paul K Sadler
Paul K Sadler - avatar