数组不断清理自己

时间:2017-11-20 07:08:33

标签: ios arrays swift

我正在尝试将值附加到可选数组中 我的空数组代码如下

var correctCards: [Int]? = nil

在viewWillAppear中我有

 let matchedIndex = (numbers.index(of: attackNumber) as! Int)

 if correctCards == nil {
    correctCards = []
 } 

 if matchedIndex == 4 {
    correctCards!.append(matchedIndex)
 } else if matchedIndex ==5 {
    correctCards!.append(matchedIndex)
 } else if and so on... 

当我运行我的代码时,我可以确认[4]在数组中。然而,当我移动到另一个viewcontroller并回到这个viewcontroller时,值被替换为new matchedIndex,例如[5]。我希望数组像[4,5]一样构建自己。我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

您必须在共享实例中维护该数组。那么只有变量的范围才不会被释放。

%{"name" => "repo",
  "pullRequests" => %{
    "nodes" => [%{
      "reviews" => %{
        "nodes" => [
          %{"author" => %{"login" => "FOO"}, "state" => "COMMENTED"},
          %{"author" => %{"login" => "FOO"}, "state" => "COMMENTED"},
          %{"author" => %{"login" => "FOO"}, "state" => "COMMENTED"},
        ]
      }
    }]
  }
}

附加数据时,您可以添加如下内容:

class DataManager: NSObject {

  static let sharedManager = DataManager()
  var correctCards : [Int] = []

}

答案 1 :(得分:0)

尝试将代码移到viewDidLoad(而不是viewWillAppear)中:

override func viewDidLoad() {
  super.viewDidLoad()

  let matchedIndex = (numbers.index(of: attackNumber) as! Int)
  if correctCards == nil {
     correctCards = []
  } 

  if matchedIndex == 4 {
    correctCards!.append(matchedIndex)
  } else if matchedIndex ==5 {
    correctCards!.append(matchedIndex)
  } else if and so on...
}