diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index f804f3d40..cceeb6ff9 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -89,7 +89,9 @@ public protocol EncodableRecord { /// /// struct Player: PersistableRecord, Encodable { /// // Customize the encoder name when encoding a database row - /// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"] + /// static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { + /// [encoderName: "Database"] + /// } /// /// func encode(to encoder: Encoder) throws { /// // Print the encoder name @@ -108,6 +110,23 @@ public protocol EncodableRecord { /// encoder.userInfo = [encoderName: "JSON"] /// let data = try encoder.encode(player) /// ``` + /// + /// > Important: Make sure the `databaseEncodingUserInfo` property is + /// > explicitly declared as `[CodingUserInfoKey: Any]`. If it is not, + /// > the Swift compiler may silently miss the protocol requirement. + /// + /// > Important: Make sure the property is declared as a computed + /// > property (`static var`), instead of a stored property + /// > (`static let`). Computed properties avoid a compiler diagnostic + /// > with stored properties: + /// > + /// > ```swift + /// > // static property 'databaseEncodingUserInfo' is not + /// > // concurrency-safe because non-'Sendable' type + /// > // '[CodingUserInfoKey: Any]' may have shared + /// > // mutable state. + /// > static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"] + /// > ``` static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get } /// Returns the `JSONEncoder` that encodes the value for a given column. diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 339a4a497..b5f50cebf 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -746,9 +746,12 @@ extension MutablePersistableRecordEncodableTests { case nestedKeyed, nestedSingle, nestedUnkeyed, key, context } - static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [ - testKeyRoot: "GRDB root", - testKeyNested: "GRDB nested"] + static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { + [ + testKeyRoot: "GRDB root", + testKeyNested: "GRDB nested", + ] + } static func databaseJSONEncoder(for column: String) -> JSONEncoder { let encoder = JSONEncoder() @@ -905,7 +908,9 @@ extension MutablePersistableRecordEncodableTests { struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" - static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [CodingUserInfoKey.testKey: "correct"] + static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { + [CodingUserInfoKey.testKey: "correct"] + } let nested: NestedStruct? }