自学敏捷,所以在这里很完整,但是我很想做一个项目,只是知道必须有一种更简单的方法来实现目标。
我有一个二维数组:
var shopArray = [
["theme":"default","price":0,"owned":true,"active":true,"image":UIImage(named: "defaultImage")!,"title":"BUY NOW"],
["theme":"red","price":1000,"owned":false,"active":false,"image":UIImage(named: "redImage")!,"title":"BUY NOW"],
["theme":"blue","price":2000,"owned":false,"active":false,"image":UIImage(named: "blueImage")!,"title":"BUY NOW"],
["theme":"pool","price":3000,"owned":true,"active":false,"image":UIImage(named: "blueImage")!,"title":"BUY NOW"],
["theme":"line","price":4000,"owned":false,"active":false,"image":UIImage(named: "lineImage")!,"title":"BUY NOW"],
["theme":"neon","price":5000,"owned":false,"active":false,"image":UIImage(named: "lineImage")!,"title":"BUY NOW"]]
在这里,我只是想创建一个运行并搜索所有“ owned”键并将其全部设置为“ false”的函数。
您如何在数组/ 2D数组中搜索和替换。更具体地说,功能应该是什么样子?
谢谢!
您可以执行类似的操作来遍历数组,替换适当的元素。
var i = 0
for x in shopArray {
var y = x
y["owned"] = false
shopArray.remove(at: i)
shopArray.insert(y, at: i)
i = i + 1
}
或您可以使用while循环以更少的代码行执行相同的操作。
var y = 0
while y < shopArray.count {
shopArray[y].updateValue(false, forKey: "owned")
y += 1
}
。可能包含很多东西,但是我不确定您是否需要达到上面提到的结果。在xcode的游戏环境中玩耍,尝试一些其他选项,而不做可能会导致项目问题的任何事情。
您没有2D数组,却有一个字典数组。
您可以通过迭代数组的索引并更新值来设置owned
键的所有值:
shopArray.indices.forEach { shopArray[$0]["owned"] = false }
这是执行此操作的功能方法。您也可以使用for
循环执行相同的操作:
for idx in shopArray.indices {
shopArray[idx]["owned"] = false
}