假设我有一个如下所示的数组:
let games = [
Game(type: "Soccer", value: 1),
Game(type: "Basket", value: 3),
Game(type: "Hockey", value: 5),
Game(type: "Soccer", value: 2),
Game(type: "Soccer", value: 4),
Game(type: "Basket", value: 2)
]
我想要一个新的数组,每个类型有1行,并且匹配类型的值互相添加。像这样:
let newGames = [
NewGame(type: "Soccer", value: 7),
NewGame(type: "Basket", value: 5),
NewGame(type: "Hockey", value: 5)
]
请帮助。我的大脑没有合作。
答案 0 :(得分:3)
struct Game {
let type: String
let value: Int
}
let games: [Game] = [
Game(type: "Soccer", value: 1),
Game(type: "Basket", value: 3),
Game(type: "Hockey", value: 5),
Game(type: "Soccer", value: 2),
Game(type: "Soccer", value: 4),
Game(type: "Basket", value: 2)
]
var totalValueForGame = [String: Int]()
for game in games {
totalValueForGame[game.type] = game.value + (totalValueForGame[game.type] ?? 0)
}
let newGames = totalValueForGame.map { Game(type: $0, value: $1) }
print(newGames)
输出:
[Game(type: "Soccer", value: 7), Game(type: "Hockey", value: 5), Game(type: "Basket", value: 5)]
答案 1 :(得分:1)
class Game {
var type: String
var value: Int
init(type: String, value: Int) {
self.type = type
self.value = value
}
}
let games: [Game] = [
Game(type: "Soccer", value: 1),
Game(type: "Basket", value: 3),
Game(type: "Hockey", value: 5),
Game(type: "Soccer", value: 2),
Game(type: "Soccer", value: 4),
Game(type: "Basket", value: 2)
]
var gameTotals:[Game] = []
for key in Set(games.map{$0.type}) {
gameTotals.append(Game(type: key, value: games.filter{$0.type == key}.reduce(0){$0+$1.value}))
}
gameTotals // [{type "Soccer", value 7}, {type "Hockey", value 5}, {type "Basket", value 5}]
答案 2 :(得分:0)
我(丑陋)的解决方案:D:D
import Cocoa
class Game {
var name:String
var value:Int
init(withName aName:String, andValue value:Int) {
self.name = aName
self.value = value
}
}
var someSports:[Game] = []
var tempDictOfGames:[String:Int] = [:]
var sports:[String] = ["Soccer", "Volleyball", "Tennis", "Rugby", "Tennis", "Soccer", "Tennis", "Cricket"]
var values:[Int] = [1, 5, 3, 8, 2, 9, 4, 7]
for (var i = 0; i < sports.count; i++) {
var availableGameValue:Int? = tempDictOfGames[sports[i]]
if let myValue = availableGameValue {
tempDictOfGames[sports[i]]! += values[i]
} else {
tempDictOfGames[sports[i]] = values[i]
}
}
for (k, v) in tempDictOfGames {
let newGame = Game(withName: k, andValue: v)
someSports.append(newGame)
}