Skip to content

Commit e3f021c

Browse files
authored
Merge pull request #1711 from ddunn2/valueForKey
2 parents edfee4a + 6222889 commit e3f021c

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Foundation/NSDictionary.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,12 @@ open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding,
3333
}
3434

3535
open func value(forKey key: String) -> Any? {
36-
NSUnsupported()
36+
if key.hasPrefix("@") {
37+
NSUnsupported()
38+
} else {
39+
return object(forKey: key)
40+
}
41+
3742
}
3843

3944
open func keyEnumerator() -> NSEnumerator {

TestFoundation/TestNSDictionary.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ class TestNSDictionary : XCTestCase {
2121
("test_writeToFile", test_writeToFile),
2222
("test_initWithContentsOfFile", test_initWithContentsOfFile),
2323
("test_settingWithStringKey", test_settingWithStringKey),
24+
("test_valueForKey", test_valueForKey),
25+
("test_valueForKeyWithNestedDict", test_valueForKeyWithNestedDict),
2426
]
2527
}
2628

@@ -217,6 +219,19 @@ class TestNSDictionary : XCTestCase {
217219
// has crashed in the past
218220
dict["stringKey"] = "value"
219221
}
222+
223+
func test_valueForKey() {
224+
let dict: NSDictionary = ["foo": "bar"]
225+
let result = dict.value(forKey: "foo")
226+
XCTAssertEqual(result as? String, "bar")
227+
}
228+
229+
func test_valueForKeyWithNestedDict() {
230+
let dict: NSDictionary = ["foo": ["bar": "baz"]]
231+
let result = dict.value(forKey: "foo")
232+
let expectedResult: NSDictionary = ["bar": "baz"]
233+
XCTAssertEqual(result as? NSDictionary, expectedResult)
234+
}
220235

221236
private func createTestFile(_ path: String, _contents: Data) -> String? {
222237
let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"

0 commit comments

Comments
 (0)