-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Open
Labels
FoundationbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.A deviation from expected or documented behavior. Also: expected but undesirable behavior.not a bugResolution → not a bug: Reported as a bug but turned out to be expected behavior or programmer errorResolution → not a bug: Reported as a bug but turned out to be expected behavior or programmer errorswift 5.7transfer candidateThe issue may belong in another repositoryThe issue may belong in another repository
Description
struct Name: RawRepresentable, Codable, Hashable {
typealias RawValue = String
var rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
var hashValue: Int {
return rawValue.hashValue
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let rawValue = try container.decode(String.self)
self.init(rawValue: rawValue)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
let value0 = Name.init(rawValue: "Name")
let encoder0 = JSONEncoder()
if let data = try? encoder0.encode(value0) {
if let string = String(data: data, encoding: .utf8) {
print(string) // ✅ prints: "Name"
}
}
let value1 = [Name.init(rawValue: "Name"): "John"]
let encoder1 = JSONEncoder()
if let data = try? encoder1.encode(value1) {
if let string = String(data: data, encoding: .utf8) {
print(string) // ❌ prints: ["Name","John"]
}
}
let value2 = ["Name": Name.init(rawValue: "John")]
let encoder2 = JSONEncoder()
if let data = try? encoder2.encode(value2) {
if let string = String(data: data, encoding: .utf8) {
print(string) // ✅ prints: {"Name":"John"}
}
}
Environment
- Swift compiler version info
- Xcode version info Xcode 14.2 Build version 14C18
- Deployment target: iOS
- swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
Metadata
Metadata
Assignees
Labels
FoundationbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.A deviation from expected or documented behavior. Also: expected but undesirable behavior.not a bugResolution → not a bug: Reported as a bug but turned out to be expected behavior or programmer errorResolution → not a bug: Reported as a bug but turned out to be expected behavior or programmer errorswift 5.7transfer candidateThe issue may belong in another repositoryThe issue may belong in another repository