Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 阵列不断清除自身_Ios_Arrays_Swift - Fatal编程技术网

Ios 阵列不断清除自身

Ios 阵列不断清除自身,ios,arrays,swift,Ios,Arrays,Swift,我正在尝试将值附加到可选数组中。 我的空数组代码如下所示 var correctCards: [Int]? = nil 在我看来我有 let matchedIndex = (numbers.index(of: attackNumber) as! Int) if correctCards == nil { correctCards = [] } if matchedIndex == 4 { correctCards!.append(matchedIndex) }

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

var correctCards: [Int]? = nil
在我看来我有

 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时,该值将替换为新的matchedIndex,例如[5]。我希望阵列能够像[4,5]那样自行构建。我的代码有什么问题?

尝试将代码移动到
viewdiload
(而不是viewwillbeen):


您必须在共享实例中维护阵列。那么只有变量的作用域不会被释放

class DataManager: NSObject {

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

}
追加数据时,可以追加如下内容:

 DataManager.sharedManager.correctCards.append(matchedIndex)

将数据模型保持在控制器外部,并且在更改控制器时不要重置它。如何“返回到此viewcontroller”?听起来您正在创建初始值的新实例controller@Satsuki您可以使用Singleton类在两个视图控制器中使用单个属性。顺便说一句,无需强制将数组索引强制转换为Int。数组索引它已经是一个
Int
,您还可以将correctCards设置为非可选,并用空数组初始化它。这不起作用-关键是每次返回初始控制器时都要构建阵列-这只会附加一个entry@Russell这可能会起作用,因为viewcontroller在呈现新vc时没有Denit,如果他从呈现的vc返回,则不会调用viewDidLoad,但如果他关闭此vc,然后值将丢失,最安全的方法仍然是使其成为单例或移动到不同的类
 DataManager.sharedManager.correctCards.append(matchedIndex)