按下按钮时创建新数组

Create new array when button is pressed

提问人:Marc S. 提问时间:11/15/2023 最后编辑:HangarRashMarc S. 更新时间:11/16/2023 访问量:76

问:

我想在每次按下按钮 (ActionButton) 时创建一个新数组。第一次按下此按钮时,应创建一个新数组并添加 10。当第二次按下按钮时,应创建另一个新数组并添加 20。等等。我还想将创建的数组保存在 Core Data 中。 在这种情况下,发生了指定的错误。但是当从 to 更改为 then 时,它只有 1 个数组,并且每次都会被覆盖,对吧? 你能不能这么好心,告诉我哪个代码是正确的,可以创建一个新数组,添加当前值,然后保存它。letvar

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)
        }
    }
}
阵列 swift core-data uikit

评论

0赞 Fogmeister 11/15/2023
只是一个评论。 这里不是按钮,而是点击按钮时调用的函数,应以小写字母开头。类似的东西会是它的好名字。ActionButtonactionButtonTapped
0赞 Fogmeister 11/15/2023
您不能附加到 ,因为它是 .我不确定你关于使用的评论指的是什么?但是,如果要添加到 ,那么它需要是 not a .newarrayletvarnewarrayvarlet
0赞 Fogmeister 11/15/2023
话虽如此......your will 只包含一个值。你能解释一下你一般想做什么吗,我也许可以帮忙。newarray
0赞 HangarRash 11/15/2023
请不要添加 Xcode 标签。您的问题不是询问 Xcode 的功能。
0赞 Marc S. 11/15/2023
@Fogmeister 通常,每次点击 ActionButton 时,我都会尝试创建一个新数组。在这个新数组中,应追加当前值。第一个 tapp = [10],第二个 tapp = [20],第三个 tapp = [30],依此类推。此数组应保存在 CoreData 中。感谢您的帮助。

答:

1赞 DonMag 11/15/2023 #1

目前尚不清楚为什么需要多个单元素数组,但假设您有正当理由......

您想使用“数组的数组”。每次点击按钮时,您都会将一个新数组附加到“数组的数组”中:

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]]

-----------

编辑 - 回答评论...

如果要为每个“子数组”添加 5 个数字,我们可以添加一个属性来跟踪“主”数组中的子数组。currentIndex

当我们将 5 个数字附加到 currentIndex 的数组中时,我们将递增 currentIndex 并将一个新的空数组附加到“main”数组中。

class ViewContoller: UIViewController {
    
    var number : Double = 0
    var theArrays: [[Double]] = []
    
    // to track which sub-array we're appending new numbers to
    var currentIndex: Int = 0
    
    @IBAction func ActionButton(_ sender: UIButton) {
        
        number += 10.0
        
        // if theArrays is empty
        if theArrays.isEmpty {
            // that means this is the very first time button was tapped
            //  so append an empty array to theArrays
            theArrays.append([])
            // set currentIndex to Zero, in case
            //  it has been changed somewhere else
            currentIndex = 0
        }

        // if the array at currentIndex has 5 elements
        if theArrays[currentIndex].count == 5 {
            // increment currentIndex
            currentIndex += 1
            // append an empty array to theArrays
            theArrays.append([])
        }
        
        // append number to the array at currentIndex
        theArrays[currentIndex].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("-----------")
    }

}

现在,点击 27 次后,我们将在调试控制台中看到以下内容:

-----------

Array 0: [10.0, 20.0, 30.0, 40.0, 50.0]
Array 1: [60.0, 70.0, 80.0, 90.0, 100.0]
Array 2: [110.0, 120.0, 130.0, 140.0, 150.0]
Array 3: [160.0, 170.0, 180.0, 190.0, 200.0]
Array 4: [210.0, 220.0, 230.0, 240.0, 250.0]
Array 5: [260.0, 270.0]

theArrays: [[10.0, 20.0, 30.0, 40.0, 50.0], [60.0, 70.0, 80.0, 90.0, 100.0], [110.0, 120.0, 130.0, 140.0, 150.0], [160.0, 170.0, 180.0, 190.0, 200.0], [210.0, 220.0, 230.0, 240.0, 250.0], [260.0, 270.0]]

-----------

评论

0赞 Marc S. 11/16/2023
感谢您的解释和代码。以下情况可能吗?: 第一次按下按钮时,将创建一个新数组,其中包含以下数字: Array0: [10.0] 要再按 4 次,则数字将附加到 Array0: [10.0, 20.0, 30.0, 40.0, 50.0]。当按下六次时,将创建一个新的 Array1,其编号为:Array1:[60.0] 但是使用“let”数组,.append 是不可能的,我得到命名错误。
0赞 DonMag 11/16/2023
@MarcS。- 请参阅编辑我的答案。
0赞 Marc S. 11/17/2023
非常感谢,您的代码和解释对我有很大帮助。