例:リファレンスタイプでCodableプロトコルを使用するにはどうすればよいですか?
import Foundation
class Player: Codable {
let name: String
init(name: String) {
self.name = name
}
}
class Team: Codable {
let players: [Player]
let capitan: Player
init(players: [Player], capitan: Player) {
self.players = players
self.capitan = capitan
}
}
let player1 = Player(name: "p1")
let player2 = Player(name: "p2")
let team = Team(players: [player1, player2], capitan: player1)
print(team.players[0] === team.capitan) // true
let encoder = JSONEncoder()
let data = try encoder.encode(team)
let decoder = JSONDecoder()
let team2 = try decoder.decode(Team.self, from: data)
print(team2.players[0] === team2.capitan) // false
出力:参照型でコード可能なプロトコルを使用する方法
true
false
?
今後の動作は変わることがありますか? https://github.com/apple/swift-evolution/blob/master/proposals/0167-swift-encoders.md
参照型が必要です – rtnm