以前的数组登录大小帽后创建新数组



我最近开始在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 = ""

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

有人想法吗?谢谢!daan

您是否要保留旧的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 oterator ??如果可用,请在左侧使用可选值,否则右侧的默认值:

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 = ""

最新更新