【发布时间】:2017-01-26 11:52:16
【问题描述】:
我刚刚完成了一大段代码的编码,尽管它运行良好,但问题是每当我调用编写代码的方法时,代码都会运行两次。复制整个代码块可能没有用,因为它只会让您感到困惑,但我可以解释代码的结构。我怀疑问题出在方法的结构上。
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
代码非常复杂,包含大量个人信息,所以很遗憾我不能在这里复制并发布,但我希望它的简化版本仍然可以让每个人都能理解它。我正在处理的问题是,只有代码的最后一部分(我假设,但不确定)被执行了两次,这意味着我想要存储在数据库中的任何内容都会被存储两次。我还在代码末尾发生了视图转换,它也被触发了两次,所以基本上每当调用此方法时,我都会看到视图转换在瞬间发生两次。我假设它只运行代码的最后一部分两次的原因是因为我假设它与 for-in 循环有关(发生在过程中途的某个地方)。我认为这是我可以检查从数据库检索的字典数组中的每个单独字典的唯一方法,但问题是用于将数据存储在数据库中的代码也写在 for-in 循环中。因此,每当循环决定再次运行(出于某种原因)时,它可能会再次执行真正的“else”语句,从而导致 else 语句中的每个代码都被执行两次。谁能纠正我或确认这确实是我的问题的原因?只有,如果是的话,我是否还可以获得一些关于在不使用 for-in 循环的情况下运行字典数组的最有效方法的提示?
【问题讨论】:
标签: ios arrays swift loops dictionary