在上一个数组达到大小上限后创建新数组

时间:2016-12-29 10:57:14

标签: arrays swift xcode xcode8

我最近开始使用xCode 8进行开发,但经验不足。

在我的应用程序中,用户可以将三个数字发送到“得分”数组。在数组n1中存储了三个数字之后,我希望将以下三个分数保存在数组n2中,依此类推。

目前,我的代码如下所示。

   var shots = [Int]()

   @IBAction func SaveScores(_ sender: UIButton) {        
        let first:Int? = Int(firstScore.text!)
        let second:Int? = Int(secondScore.text!)
        let third:Int? = Int(thirdScore.text!)

        shots.append(first!)
        shots.append(second!)
        shots.append(third!)

        firstScore.text = ""
        secondScore.text = ""
        thirdScore.text = ""

在第一个数组包含三个元素之后,我正在努力初始化一个新数组。

任何想法?谢谢! 大安

1 个答案:

答案 0 :(得分:1)

您想保留旧的shots数组吗?如果没有,您应该只能覆盖现有的数组:

shots = []

否则,您需要将shots数组存储在另一个数组中:

var shots: [[Int]] = []

@IBAction func SaveScores(_ sender: UIButton) {     
    let first:Int? = Int(firstScore.text!)
    let second:Int? = Int(secondScore.text!)
    let third:Int? = Int(thirdScore.text!)

    let scores = [first!, second!, third!]

    shots.append(scores)

    firstScore.text = ""
    secondScore.text = ""
    thirdScore.text = ""

这是相同的代码,更强大的选项处理。如果可用,nil-coalescing运算符??在左侧获取可选值,否则在右侧使用默认值:

var shots: [[Int]] = []

@IBAction func SaveScores(_ sender: UIButton) {
    guard let first = Int(firstScore.text ?? ""),
          let second = Int(secondScore.text ?? ""),
          let third = Int(thirdScore.text ?? "")
    else {
        // error handling
        return
    }

    let scores = [first, second, third]

    shots.append(scores)

    firstScore.text = ""
    secondScore.text = ""
    thirdScore.text = ""