Skip to content

Commit

Permalink
Command line arguments support
Browse files Browse the repository at this point in the history
  • Loading branch information
Kenneth P. Wong committed Jun 18, 2022
1 parent 5d10c31 commit 880af40
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
30 changes: 22 additions & 8 deletions Sources/UserDefaults+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,28 @@ extension UserDefaults {
func fetchOptional<T: UserDefaultsSerializable>(_ key: String) -> T? {
let fetched: Any?

if T.self == URL.self {
// Hack for URL, which is special
// See: http://dscoder.com/defaults.html
// Error: Could not cast value of type '_NSInlineData' to 'NSURL'
fetched = self.url(forKey: key)
} else {
fetched = self.object(forKey: key)
}
// to support command line arguments, some types need explicit getter methods
// otherwise, errors like "Could not cast value of type '__NSCFString' to 'NSNumber'." occur
//
// but check first for the nil case
if self.object(forKey: key) == nil {
fetched = nil
} else {
switch T.self {
case is Bool.Type:
fetched = self.bool(forKey: key)
case is Int.Type:
fetched = self.integer(forKey: key)
case is Float.Type:
fetched = self.float(forKey: key)
case is Double.Type:
fetched = self.double(forKey: key)
case is URL.Type:
fetched = self.url(forKey: key)
default:
fetched = self.object(forKey: key)
}
}

if fetched == nil {
return nil
Expand Down
14 changes: 14 additions & 0 deletions Tests/TestSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,18 @@ final class TestSettings: NSObject {

@WrappedDefaultOptional(key: "userId", userDefaults: store)
@objc dynamic var userId: String?

//

@WrappedDefaultOptional(key: "boolArg", userDefaults: store)
var boolArg: Bool?

@WrappedDefaultOptional(key: "intArg", userDefaults: store)
var intArg: Int?

@WrappedDefaultOptional(key: "floatArg", userDefaults: store)
var floatArg: Float?

@WrappedDefaultOptional(key: "doubleArg", userDefaults: store)
var doubleArg: Double?
}

0 comments on commit 880af40

Please sign in to comment.