我想每次按下按钮(ActionButton)时创建一个新数组。第一次按下此按钮时,应创建一个新数组并添加 10。当第二次按下按钮时,应创建另一个新数组并添加 20。依此类推。我还想将创建的数组保存在核心数据中。 在这种情况下,发生了指定的错误。但是当从
let
更改为 var
时,它就只有 1 个数组,并且每次都会被覆盖,对吗?
您能否善意地告诉我哪些代码适合创建一个新数组,添加当前值并保存它。
import UIKit
import CoreData
class ViewController: UIViewController {
var number : Double = 0
// Reference to Managed Object Context
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var average : Stats?
var array : Stats?
//-------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
fetchStats()
}
//-------------------------------------------------------------------------------------
@IBAction func ActionButton(_ sender: UIButton) {
number += 10.0
average?.value = number
//Idea
let newarray = [Double]()
newarray.append(number)
array?.new = newarray
//Error message by .append:
//Cannot use mutatingChange 'let' to 'var' to make it mutable member on immutable value: 'TestArray' is a 'let' constant
//Change 'let' to 'var' to make it mutable
saveData()
}
//-------------------------------------------------------------------------------------
func fetchStats() {
//Fetch the data from CoreData to display in the View
do {
if let found = try context.fetch(Stats.fetchRequest()).first {
average = found
number = found.value
array = found
newarray = found.new
} else {
average = Stats(context: context)
average?.value = 0
array = Stats(context: context)
array?.new = []
saveData()
}
}
catch {
print(error)
}
}
//-------------------------------------------------------------------------------------
func saveData() {
do {
try context.save()
} catch {
print(error)
}
}
}
不清楚为什么你想要多个单元素数组,但假设你有一个有效的理由......
您想使用“数组的数组”。每次点击按钮,您都会将一个新数组附加到“数组的数组”中:
class ViewContoller: UIViewController {
var number : Double = 0
var theArrays: [[Double]] = []
@IBAction func ActionButton(_ sender: UIButton) {
number += 10.0
theArrays.append([number])
print() // blank line
for i in 0..<theArrays.count {
print("Array \(i):", theArrays[i])
}
print() // blank line
print("theArrays:", theArrays)
print() // blank line
print("-----------")
}
}
如果点击按钮 4 次,您将在调试控制台中看到以下内容:
Array 0: [10.0]
theArrays: [[10.0]]
-----------
Array 0: [10.0]
Array 1: [20.0]
theArrays: [[10.0], [20.0]]
-----------
Array 0: [10.0]
Array 1: [20.0]
Array 2: [30.0]
theArrays: [[10.0], [20.0], [30.0]]
-----------
Array 0: [10.0]
Array 1: [20.0]
Array 2: [30.0]
Array 3: [40.0]
theArrays: [[10.0], [20.0], [30.0], [40.0]]
-----------