ios - 在 Swift 中运行两次的检查数据和存储数据的代码

标签 ios arrays swift loops dictionary

我刚刚完成了一大段代码的编码,尽管它运行良好,但问题是每当我调用编写代码的方法时,代码都会运行两次。复制整个代码块可能没有用,因为它只会让您感到困惑,但我可以解释代码的结构。我怀疑问题出在方法的结构上。

func methodName {

    if thisConditionIsTrue {

        // This condition is true, so it gets executed: it retrieves an array of dictionaries from the database

        for-in loop {
            // This loop runs through all of the retrieved dictionary objects

            if dictionaryMeetsThisRequirement {
                // False condition, so it doesn't get executed
            else if dictionaryMeetsThisRequirement {
                // False condition, so it doesn't get executed
            else if dictionaryMeetsThisRequirement {
                // False condition, so it doesn't get executed
            else {
                // True condition, so it gets executed: now it stores data form the client into the database

代码非常复杂,包含大量个人信息,所以很遗憾,我不能复制它并张贴在这里,但我希望这个简化版本仍然足以让每个人都能理解。我正在处理的问题是,只有代码的最后一部分(我假设,但不确定)被执行了两次,这意味着我想要存储在数据库中的任何内容都被存储了两次。我还在代码末尾发生了 View 转换,它也被触发了两次,所以基本上每当调用此方法时,我都会看到 View 转换在瞬间发生两次。我假设它只运行代码的最后一部分两次的原因是因为我假设它与 for-in 循环有关(它发生在过程中途的某个地方)。我想这是我可以检查从数据库中检索到的字典数组中每个单独的字典的唯一方法,但问题是用于将数据存储在数据库中的代码也写在 for-in 循环中。因此,每当循环决定再次运行(出于某种原因)时,它可能会再次执行真正的“else”语句,导致 else 语句中的每个代码都被执行两次。任何人都可以纠正我或确认这可能确实是我的问题的原因?而且,如果是的话,我还能得到一些关于在不使用 for-in 循环的情况下运行字典数组的最有效方法的提示吗?

最佳答案

您不需要使用 for in 循环,因为字典是无序的,这就是美妙之处。您唯一需要做的就是

1.如果你想检查一个key是否存在于字典中

if  dictionary[keyname] != nil {
   //perform some action
}

2.如果你想检查键的值是否等于你正在检查的某个变量

if  dictionary[keyname] == variableYouAreCheckingAgainst {
   //perform some action
}

关于ios - 在 Swift 中运行两次的检查数据和存储数据的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39562182/

相关文章:

ios - 如何开发iOS模拟器插件

c++ - 使用 '='运算符在C++中使两个数组相等

c - 为什么带星号和不带星号的指针变量在 printf 中表现不同?

ios - 在 Xcode 6.0 中导入 .xliff 本地化文件

ios - entityForName :nil Issue

javascript - jQuery - 使用 inArray() 查找 jQuery 对象的索引

objective-c - 等待异步函数完成

ios - 向圆圈添加模糊阴影

swift - CollectionViewCell 未显示从 Firebase 接收数据

ios - (CoreData) MagicalRecord 突然停止持久保存