简体   繁体   English

在 Swift 的二维数组中搜索和替换字符串

[英]Search and replace string in 2D Array in Swift

Teaching myself swift, so complete noob here, but I'm far into a project and just know there must be an easier way to achieve something.自学 swift,所以在这里完成新手,但我对一个项目还很遥远,只知道必须有一种更简单的方法来实现某些目标。

I have a 2D array:我有一个二维数组:

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

Where I simply want to create a function that runs and search for all the "owned" keys and make them all "false" .我只想创建一个 function 运行并搜索所有“拥有”键并使它们全部为“false”

How do you search and replace in Arrays / 2D Arrays.如何在 Arrays / 2D Arrays 中搜索和替换。 More specifiaclly, what should the func look like?更具体地说,func 应该是什么样的?

Thank you!谢谢!

You don't have a 2D array, you have an Array of Dictionaries.你没有二维数组,你有一个字典数组。

You can set all of the values for the owned keys by iterating the indices of the Array and updating the values:您可以通过迭代数组的索引并更新值来设置owned键的所有值:

shopArray.indices.forEach { shopArray[$0]["owned"] = false }

That is the functional way to do it.这是实现它的功能性方式。 You could also do the same operation with a for loop:您也可以使用for循环执行相同的操作:

for idx in shopArray.indices {
    shopArray[idx]["owned"] = false
}

You could do something like this to loopthrough the array replacing the approriate element.你可以做这样的事情来遍历数组替换适当的元素。

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
}

or you could use a while loop to do the same with less code lines.或者您可以使用 while 循环以更少的代码行来执行相同的操作。

var y = 0
while y < shopArray.count {
    shopArray[y].updateValue(false, forKey: "owned")
    y += 1
}

There is proably somthing doable with.contains, but I'm not sure you need that toachive the result you mention above.使用.contains 可能有一些可行的方法,但我不确定你是否需要它来达到你上面提到的结果。 Play around in a play ground in xcode and try a few different options without doing anything that might cause issues in your project.在 xcode 的操场上玩耍,尝试一些不同的选项,而不做任何可能导致项目出现问题的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM