Skip to content

Commit

Permalink
Fix UserDefaults.integer(forKey:) behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
woxtu authored and compnerd committed Jul 22, 2023
1 parent c0cd1d1 commit 8fbe624
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Sources/Foundation/UserDefaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,15 @@ open class UserDefaults: NSObject {
if let bVal = aVal as? Int {
return bVal
}
if let bVal = aVal as? Bool {
return NSNumber(value: bVal).intValue
}
if let bVal = aVal as? Float {
return NSNumber(value: bVal).intValue
}
if let bVal = aVal as? Double {
return NSNumber(value: bVal).intValue
}
if let bVal = aVal as? String {
return NSString(string: bVal).integerValue
}
Expand Down
30 changes: 30 additions & 0 deletions Tests/Foundation/Tests/TestUserDefaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ class TestUserDefaults : XCTestCase {
("test_setValue_NSData", test_setValue_NSData ),
("test_setValue_Data", test_setValue_Data ),
("test_setValue_BoolFromString", test_setValue_BoolFromString ),
("test_setValue_IntFromBool", test_setValue_IntFromBool ),
("test_setValue_IntFromFloat", test_setValue_IntFromFloat ),
("test_setValue_IntFromDouble", test_setValue_IntFromDouble ),
("test_setValue_IntFromString", test_setValue_IntFromString ),
("test_setValue_DoubleFromString", test_setValue_DoubleFromString ),
("test_setValue_StringFromBool", test_setValue_StringFromBool ),
Expand Down Expand Up @@ -231,6 +234,33 @@ class TestUserDefaults : XCTestCase {
XCTAssertEqual(defaults.bool(forKey: "key1"), true)
}

func test_setValue_IntFromBool() {
let defaults = UserDefaults.standard

// Register an int default value as a boolean. UserDefaults.integer(forKey:) is supposed to return the converted Int value
defaults.set(true, forKey: "key1")

XCTAssertEqual(defaults.integer(forKey: "key1"), 1)
}

func test_setValue_IntFromFloat() {
let defaults = UserDefaults.standard

// Register an int default value as a float. UserDefaults.integer(forKey:) is supposed to return the converted Int value
defaults.set(12.34 as Float, forKey: "key1")

XCTAssertEqual(defaults.integer(forKey: "key1"), 12)
}

func test_setValue_IntFromDouble() {
let defaults = UserDefaults.standard

// Register an int default value as a double. UserDefaults.integer(forKey:) is supposed to return the converted Int value
defaults.set(12.34, forKey: "key1")

XCTAssertEqual(defaults.integer(forKey: "key1"), 12)
}

func test_setValue_IntFromString() {
let defaults = UserDefaults.standard

Expand Down

0 comments on commit 8fbe624

Please sign in to comment.