gpt4 book ai didi

arrays - 如何使用变量将字符串追加到数组中? swift

转载 作者:搜寻专家 更新时间:2023-11-01 06:02:38 24 4
gpt4 key购买 nike

我最近开始学习编码,但在将已转换为变量的字符串追加到数组中时遇到了问题。这是控制台说的:

无法将“[String]”类型的值转换为预期的参数类型“String”

这是我的代码:

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]
}

最佳答案

只需将您的代码更改为:

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

randomList.append(contentsOf: item)

return "\(item) was added"
}

然后你将能够像这样添加 1 个或多个字符串:

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

生成的数组将如下所示:

print(randomList)

["你好", "你", "那里"]


追加单个字符串:

let singleString = "hi"

addItem(item: singleString)

追加多个字符串:

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

addItem(item: stringOne, stringTwo, stringThree)

关于arrays - 如何使用变量将字符串追加到数组中? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com