我有2个结构(游戏,otgame(,其中包含一个名为[COD]的NSString属性。我尝试将第二个结构与[COD]相同的第一个结构相同,然后将剩余添加到队列中。
game = [cod("001234"),cod("001111"),cod("002222"),cod("005555")]
otGame = [cod("002222"),cod("005555"),cod("001111")]
struct game {
var cod: NSString
var des: Float?
}
struct otGame {
var cod: NSString
var sor: Float?
}
我希望otgame的输出为
[cod("001111"),cod("002222"),cod("005555"),cod("001234")]
我认为您应该做这样的事情:
struct Game {
var cod: String
var des: Float?
}
struct OtGame {
var cod: String
var sor: Float?
}
let games = [Game(cod: "001234", des: nil),
Game(cod: "001111", des: nil),
Game(cod:"002222", des: nil),
Game(cod:"005555", des: nil)]
var otGames = [OtGame(cod: "002222", sor: nil),
OtGame(cod: "005555", sor: nil),
OtGame(cod: "001111", sor: nil)]
//Sort otGames based on indexes of games
otGames.sort { (o1, o2) -> Bool in
if let index1 = games.firstIndex(where: {$0.cod == o1.cod}), let index2 = games.firstIndex(where: {$0.cod == o2.cod}) {
return index1 < index2
}
return false
}
// Add missing games
for game in games {
if !otGames.contains(where: {$0.cod == game.cod}) {
otGames.append(OtGame(cod: game.cod, sor: game.des))
}
}
请注意,这种性能非常不好,我建议您找到不同的数据结构或解决方案以防止此计算。