我有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")]
答案 0 :(得分:0)
我认为您应该这样做:
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))
}
}
请注意,这种类型的性能非常差,建议您寻找其他数据结构或解决方案以防止这种计算。