我最近开始使用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 = ""
在第一个数组包含三个元素之后,我正在努力初始化一个新数组。
任何想法?谢谢! 大安
答案 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 = ""