我有一个包含4个项目的默认数组。当我尝试从第二个视图添加新项时,会删除一个项目,但应添加该项目。每当触发saveNewScore时,我都应该向数组中添加一个新项。
第一个视图 我有这个数组
var playerData: [Player] = Player.createDefaultData()
前一个数组有4个默认值。 后来我有一个un wind segue IBAction
@IBAction func newPlayerData(segue: UIStoryboardSegue) {
let editor = segue.source as! playerEditor
if let newData = editor.playerData {
playerData = newData
}
displayPlayerLeaderboard()
}
前面的代码从playerEditor视图中获取一个新数组,这是我的第二个视图控制器。
对于名为 playerEditor 的第二视图,我有以下代码
// Player Array
var playerData: [Player]?
// Func to add new player to playerData
@IBAction func saveNewScore() {
if let name = nameField.text, let hometown = hometownField.text, let state = stateField.text, let score = scoreField.text, let date = dateField.text {
if name.isEmpty == false && hometown.isEmpty == false && state.isEmpty == false && score.isEmpty == false && date.isEmpty == false {
let thisScore = Int(score) ?? 300
if thisScore >= 300 || thisScore < 0 {
let alert = UIAlertController(title: "Invalid Score", message: "A Player score must between the values of 0 and 300.", preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okButton)
present(alert, animated: true)
} else if let savedPlayer = playerID, let savedData = playerData {
for (offset,player) in savedData.enumerated() {
if player.uniqueID == savedplayer {
player.name = name
player.town = hometown
player.state = state
player.score = thisScore
player.date = date
player.Data?[offset] = player
}
}
dismiss(animated: true, completion: nil)
} else {
let newPlayer = Player(name: name, town: hometown, state: state, score: thisScore, date: date, uniqueID: largestID + 1)
playerData?.append(newPlayer)
dismiss(animated: true, completion: nil)
}
} else {
let alert = UIAlertController(title: "Invalid Data", message: "Ensure that all text fields have data in them before proceeding.", preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .default, handler: nil)
// add action to alert controller
alert.addAction(okButton)
present(alert, animated: true)
}
}
}
前面的代码将一个新的Player添加到Player类型的playerData数组中,该数组从多个UITextField获取信息。
排序功能
func sortData(data: [Player]) -> [Player] {
var newData: [Player] = []
for (offset,player) in data.enumerated() {
if offset == 1 {
newData += [player]
} else {
for (offset,newPlayer) in newData.enumerated() {
if player.score >= newPlayer.score {
newData.insert(player, at: offset)
break
} else if offset == (newData.count - 1) {
newData.append(player)
}
}
}
}
return newData
}
答案 0 :(得分:0)
在下面的方法中检查newData的count
。看起来与您更新到playerData
数组的不同之处: -
@IBAction func newPlayerData(segue: UIStoryboardSegue) {
let editor = segue.source as! playerEditor
if let newData = editor.playerData {
//Check the count of newData here
playerData = newData
}
displayPlayerLeaderboard()
}