From e42659255702ba0dc5880edca7b85f0689d4da63 Mon Sep 17 00:00:00 2001 From: John Holdsworth Date: Fri, 16 Feb 2018 14:32:18 +0000 Subject: [PATCH] Fix for when key is a String rather than NSString. Otherwise you can get the following crash: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Could not cast value of type 'Swift.AnyHashable' (0x1027b3b10) to 'SwiftFoundation.NSObject' (0x101a56668). 2018-02-16 14:30:46.355774+0000 TestFoundation[7306:8715333] Could not cast value of type 'Swift.AnyHashable' (0x1027b3b10) to 'SwiftFoundation.NSObject' (0x101a56668). (lldb) up frame #9: 0x000000010165b114 SwiftFoundation`NSMutableDictionary.subscript.setter(newValue=some, key=Swift.AnyHashable @ 0x00007fff5fbfcd88, self=0x000060800e181fe0) at NSDictionary.swift:649 646 } 647 set { 648 if let val = newValue { -> 649 setObject(val, forKey: key) 650 } else { 651 removeObject(forKey: key) 652 } (lldb) up frame #10: 0x00000001004c0443 TestFoundation`static Dictionary.twEncode(data=TestFoundation.TwoWayMirror @ 0x00007fff5fbfce00, self=[Key : Value]) at TwoWayMirror.swift:386 383 #if os(Linux) 384 let key = NSString(string: key as! String) 385 #endif -> 386 dict[key] = TwoWayMirror.encode(mirror: &mirror) 387 } 388 return dict 389 } (lldb) --- Foundation/NSDictionary.swift | 2 +- TestFoundation/TestNSDictionary.swift | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Foundation/NSDictionary.swift b/Foundation/NSDictionary.swift index 18392f49d8..db0e8d6f66 100644 --- a/Foundation/NSDictionary.swift +++ b/Foundation/NSDictionary.swift @@ -586,7 +586,7 @@ open class NSMutableDictionary : NSDictionary { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } - _storage[(aKey as! NSObject)] = _SwiftValue.store(anObject) + _storage[_SwiftValue.store(aKey)] = _SwiftValue.store(anObject) } public convenience required init() { diff --git a/TestFoundation/TestNSDictionary.swift b/TestFoundation/TestNSDictionary.swift index b1435d4565..a5380de256 100644 --- a/TestFoundation/TestNSDictionary.swift +++ b/TestFoundation/TestNSDictionary.swift @@ -32,6 +32,7 @@ class TestNSDictionary : XCTestCase { ("test_mutableCopying", test_mutableCopying), ("test_writeToFile", test_writeToFile), ("test_initWithContentsOfFile", test_initWithContentsOfFile), + ("test_settingWithStringKey", test_settingWithStringKey), ] } @@ -222,6 +223,12 @@ class TestNSDictionary : XCTestCase { } } + func test_settingWithStringKey() { + let dict = NSMutableDictionary() + // has crashed in the past + dict["stringKey"] = "value" + } + private func createTestFile(_ path: String, _contents: Data) -> String? { let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/" do {