1

I recently started learning to code and I am encountering an issue with appending a string that has been turned into a variable into an array. Here is what the console said:

cannot convert value of type '[String]' to expected argument type 'String'

Here is my code:

var randomList = [String]()

func getList(inputList:Array<String>) -> Array<String>{

    randomList = inputList

    return randomList
}

func addItem(item: String...) -> String{

    randomList.append(item)

    return "\(item) was added"
}

func getItem(x: Int) -> String{
    return randomList[x]
}
1
  • 1
    That's because you are trying to append array of item to randomList. The type of item is array not String. So to put, loop through item and then append the looped value Commented Jul 13, 2017 at 4:45

3 Answers 3

3

Just change your code to:

func addItem(item: String...) -> String{

    randomList.append(contentsOf: item)

    return "\(item) was added"
}

Then you will be able to add 1 or more strings like this:

addItem(item: "Hello", "you", "there")

The resulting array will look like this:

print(randomList)

["Hello", "you", "there"]


To append a single string:

let singleString = "hi"

addItem(item: singleString)

To append a multiple strings:

let stringOne = "one"
let stringTwo = "two"
let stringThree = "three"

addItem(item: stringOne, stringTwo, stringThree)
Sign up to request clarification or add additional context in comments.

Comments

1

Because you are appending an array of strings not a single string. item is an array of strings.

You can remove the ... to append a single item.

func addItem(item: String) -> String{

    randomList.append(item)

    return "\(item) was added"
}

or if you want to append array of string use randomList.append(contentsOf: item)

func addItem(item: String...) -> String{

    randomList.append(contentsOf: item)   

    return "\(item) was added"
}

Comments

1

You are using the Variadic Parameter (...) which is treated as an array.

That's what the error message says. You are passing an array of strings where a single string is expected.

There are two solutions:

  1. Change the item argument to String:

    func addItem(item: String) -> String{
    
  2. Use the API to append the contents of an array:

    randomList.append(contentsOf: item)
    

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.