Skip to content

Commit 0b4b227

Browse files
drodriguezparkera
authored andcommitted
Fix Dimension.encode(with:) to use same key as init(coder:). (swiftlang#1682)
The encoding method and the decoding method used slightly different keys. The incorrect key made Dimension (and the subtypes) impossible to decode (and with Swift Foundation a crash since decoding cannot fail). Includes a test to check for correctly encoding/decoding cycle.
1 parent 05eaae2 commit 0b4b227

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

Foundation/Unit.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ open class Dimension : Unit {
232232
guard aCoder.allowsKeyedCoding else {
233233
preconditionFailure("Unkeyed coding is unsupported.")
234234
}
235-
aCoder.encode(self.converter, forKey:"converter")
235+
aCoder.encode(self.converter, forKey:"NS.converter")
236236
}
237237

238238
open override func isEqual(_ object: Any?) -> Bool {

TestFoundation/TestUnit.swift

+23
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,26 @@ class TestUnit: XCTestCase {
9393
}
9494

9595
}
96+
97+
class TestDimension: XCTestCase {
98+
static var allTests: [(String, (TestDimension) -> () throws -> Void)] {
99+
return [
100+
("test_encodeDecode", test_encodeDecode),
101+
]
102+
}
103+
104+
func test_encodeDecode() {
105+
let original = Dimension(symbol: "symbol", converter: UnitConverterLinear(coefficient: 1.0))
106+
107+
let encodedData = NSMutableData()
108+
let archiver = NSKeyedArchiver(forWritingWith: encodedData)
109+
original.encode(with: archiver)
110+
archiver.finishEncoding()
111+
112+
let unarchiver = NSKeyedUnarchiver(forReadingWith: encodedData as Data)
113+
let decoded = Dimension(coder: unarchiver)
114+
115+
XCTAssertNotNil(decoded)
116+
XCTAssertEqual(original, decoded)
117+
}
118+
}

TestFoundation/main.swift

+1
Original file line numberDiff line numberDiff line change
@@ -103,5 +103,6 @@ XCTMain([
103103
testCase(TestJSONEncoder.allTests),
104104
testCase(TestCodable.allTests),
105105
testCase(TestUnit.allTests),
106+
testCase(TestDimension.allTests),
106107
testCase(TestNSLock.allTests),
107108
])

0 commit comments

Comments
 (0)