Correctly set `nil` for `OptionalKey`

Fixes #8
This commit is contained in:
Sindre Sorhus 2018-05-14 15:27:35 +07:00
parent f9a74ca64a
commit 0f45f544d6
2 changed files with 9 additions and 2 deletions

View File

@ -104,9 +104,12 @@ public extension UserDefaults {
return _get(key.name)
}
set {
if let value = newValue {
_set(key.name, to: value)
guard let value = newValue else {
set(nil, forKey: key.name)
return
}
_set(key.name, to: value)
}
}

View File

@ -35,6 +35,10 @@ final class DefaultsTests: XCTestCase {
XCTAssertNil(UserDefaults.standard[key])
UserDefaults.standard[key] = true
XCTAssertTrue(UserDefaults.standard[key]!)
UserDefaults.standard[key] = nil
XCTAssertNil(UserDefaults.standard[key])
UserDefaults.standard[key] = false
XCTAssertFalse(UserDefaults.standard[key]!)
}
func testKeys() {