Strange static string constant behaviour in swift - swift

I'm declaring two strings
public static let FILTER_PERIODS_KEY = "fi_pe"
public static let FILTER_PERIODS_DEFAULT = "M1,M5,M15,M30,H1,H4,D1"
and use them that way:
if (preferences.object(forKey: InAppProperties.FILTER_PERIODS_KEY) == nil) {
preferences.set(InAppProperties.FILTER_PERIODS_DEFAULT, forKey: InAppProperties.FILTER_PERIODS_KEY)
}
For some reason FILTER_PERIODS_KEY is not empty, while FILTER_PERIODS_DEFAULT is empty.
What is this?

The code looks correct: FILTER_PERIODS_DEFAULT is used as value and FILTER_PERIODS_KEY is used as key.
However your way to define default values for UserDefaults is wrong.
As soon as possible (in awakeFromNib or applicationWillFinishLaunching) add
let defaults = UserDefaults.standard
let defaultValues = [InAppProperties.FILTER_PERIODS_KEY: "M1,M5,M15,M30,H1,H4,D1"]
defaults.register(defaults: defaultValues)
The code has to be executed every time the application launches even if the value has changed meanwhile.

Related

No exact matches in call to initializer when initializing Data in AppStorage

I'm learning how to store custom types in AppStorage, and came across an issue. In this simplified example, I'm trying to save an empty Int array to AppStorage once the view is created.
The following code gives me the error, No exact matches in call to initializer . I know that this error usually means there are mismatching types somewhere, but I'm not sure what the types should be, or how to fix it.
struct test: View {
init() {
let emptyList = [Int]()
guard let encodedList = try? JSONEncoder().encode(emptyList) else { return }
self.storedList = encodedList
}
#AppStorage("stored_list") var storedList: Data //NO EXACT MATCHES TO CALL IN INITIALIZER
//"body" implementation not shown
}
Why is this error occurring, and how can I fix it?
It should be either with default value or optional, so correct variants are
#AppStorage("stored_list") var storedList: Data = Data()
or
#AppStorage("stored_list") var storedList: Data?

Swift: if is let redundancy

I just joined a project that has a lot of existing code. The previous programmer was perhaps unfamiliar with Swift or began development in the early stages of the Swift language. They seemed to be using the if let statement in an odd way. They seemed to want to use the statement as a if is let. Before I edit the code I would like to know if there is any valid use for this:
// In JSON parser
if value is String, let string = value as? String {
document.createdBy = string
}
First checking if value is of type String seems redundant to me. Doesn't Swift check for this in the let string = value as? String portion of the statement?
QUESTION
Why would this need to be checked twice? Or would there be a reason for this?
You're correct, this is redundant. If value is not a string, then value as? String would return nil, and the conditional binding would fail.
To check the type, and not use the casted result:
if value is String {
// Do something that doesn't require `value` as a string
}
To check the type and use the result:
if let value = value as? String { // The new name can shadow the old name
document.createdBy = value
}
Doing both makes no sense.

most concise way of unwrapping and casting optional

I have a bit of code to get a string out of userDefaults:
if let userString = (userDefaults.objectForKey("user")) {
userTextField.stringValue = userString as! String
}
First, I have to see if the optional is not nil. Then I have to cast it as a string from AnyObject.
Is there a better way of doing this? maybe a one liner?
Note that your forced cast as! String will crash if a default value for the key "user" exists, but
is not a string. Generally, you can combine optional binding (if let) with an optional cast (as?):
if let userString = userDefaults.objectForKey("user") as? String {
// ... default value for key exists and is a string ...
userTextField.stringValue = userString
}
But actually NSUserDefaults has a dedicated method for that purpose:
if let userString = userDefaults.stringForKey("user") {
// ... default value for key exists and is a string ...
userTextField.stringValue = userString
}
If you want to assign a default string in the case that
the default does not exist, or is not a string, then use the
nil-coalescing operator ??, as demonstrated in
Swift issue with nil found while unwrapping an Optional value NSDefautlts, e.g.:
userTextField.stringValue = userDefaults.stringForKey("user") ?? "(Unknown)"
For the special case NSUserDefaults the best – and recommended – way is to use always non-optional values.
First register the key / value pair in AppDelegate as soon as possible but at least before using it.
let defaults = NSUserDefaults.standardUserDefaults()
let defaultValues = ["user" : ""]
defaults.registerDefaults(defaultValues)
The benefit is you have a reliable default value of an empty string until a new value is saved the first time. In most String cases an empty string can be treated as no value and can be easily checked with the .isEmpty property
Now write just
userTextField.stringValue = userDefaults.stringForKey("user")!
Without arbitrary manipulation of the defaults property list file the value is guaranteed to be never nil and can be safely unwrapped, and when using stringForKey there is no need for type casting.
Another way that i like much to clean this up is to do each of your checks
first, and exit if any aren’t met. This allows easy understanding of what
conditions will make this function exit.
Swift has a very interesting guard statements which can also be used to avoid force unwrap crashes like :
guard let userString = userDefaults.objectForKey("user") as? String else {
// userString var will accessible outside the guard scope
return
}
userTextField.stringValue = userString
Using guards you are checking for bad cases early, making your
function more readable and easier to maintain. If the condition is not
met, guard‘s else statement is run, which breaks out of the function.
If the condition passes, the optional variable here is automatically
unwrapped for you within the scope that the guard statement was
called.

Thread 1: EXC_BAD INSTRUCTION with NSUserDefaults

I have it so that when my game ends, it switches to a separate SKScene which shows the new high score. Here is my code:
func saveState() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highScore, forKey: "labelScore") //this line says "unexpectedly found nil while unwrapping an optional value
defaults.setInteger(stars, forKey: "SNOW")
NSUserDefaults.standardUserDefaults().synchronize()
}
What could be nil? I have values for everything in this function. Will post more code if necessary.
This means that it was probably saved wrong to begin with. I would recommend using constants for things such as accessing user defaults so that this type of thing doesn't happen.
EDIT:
What I usually do is create a separate file that is a global constants file as part of a struct
In this file you can define constants like so:
struct GlobalConstants {
static let defaultsHighScore = "labelScore"
}
Then, when I try to read from defaults, instead of typing in everything every time, I can just use the constant like this: defaults.setInteger(highScore, forKey: GlobalConstants.defaultsHighScore)

Swift NSUserDefaults first time nil

Hi my app crashes the first time I run it. This is my code:
let State = save.stringForKey("StateSave")
let City = save.stringForKey("CitySave")
let Vehicle = save.stringForKey("ModelNumberSave")
let ExtensionPeriod = save.stringForKey("ExtensionPeriodChoosed")
let Location = "Location"
if ExtensionPeriod == nil {
let name = ""
var FieldChoosed: Void = save.setObject(name, forKey: "ExtensionPeriodChoosed")
save.synchronize()
}
save.synchronize()
var DetailNames = ["\(State!)","\(City!)","\(Location)","\(Vehicle!)","\(ExtensionPeriod!)"]
I get a nil on this line:
var DetailNames =
["(State!)","(City!)","(Location)","(Vehicle!)","(ExtensionPeriod!)"]
In fact ExtensionPeriod is nil. But I don't understand why... ExtensionPeriod is nil, but with the code I write, ExtensionPeriod will be like "" so it's not nil. Please help me.
stringForKey returns nil when there has not been a value saved already.
You need to give your values a default. The easiest way to do this is with the ?? operator, that replaces nil with another value:
let State = save.stringForKey("StateSave") ?? "-"
Some general advice: you need to stop using ! so much. Usually when something returns nil, it’s for a good reason – it might be nil. When you unwrap it with !, your program will crash (with not much helpful info as to why). Similarly, it’s usually a bad sign if you’re comparing values to nil.
Instead, take a look at this list of optional handling techniques for some alternatives.
Airspeed Velocity has a good solution for the proper way to accomplish what you want to do, but he did not really explain why what you did does not work, so I will address that aspect of this question.
if ExtensionPeriod == nil {
let name = ""
var FieldChoosed: Void = save.setObject(name, forKey: "ExtensionPeriodChoosed")
save.synchronize()
}
That block of code does not set ExtensionPeriod, thus ExtensionPeriod is still nil. All it does is set the value for the key "ExtensionPeriodChoosed" in the NSUserDefaults to no longer be nil. The local variable ExtensionPeriod, however, still has nil. ExtensionPeriod doesn't just magically point to the variable stored in NSUserDefaults, such that when you update NSUserDefaults, it automatically updates the variable. Instead, it copies the variable at the time that it is created.
Here is some sample code that demonstrates this:
NSUserDefaults.standardUserDefaults().setValue("string", forKey: "s")
NSUserDefaults.standardUserDefaults().synchronize()
var s = NSUserDefaults.standardUserDefaults().valueForKey("s")
NSUserDefaults.standardUserDefaults().setValue("string2", forKey: "s")
NSUserDefaults.standardUserDefaults().synchronize()
var y = NSUserDefaults.standardUserDefaults().valueForKey("s")
println(s)
println(y)
outputs:
"string"
"string2"
For your code to work, if you were to keep it the same structure (although you really shouldn't), you would need to change ExtensionPeriod to a var, and then in your if block, after you synchronize save, you would have to reassign ExtensionPeriod to save.valueForKey("ExtensionPeriodChoosed").
One way to make sure that your app's defaults are set is to use NSUserDefault's registerDefaults(_: [NSObject : AnyObject]) function. In Objective-C, I often put in the + (void)initialize class method, but overriding the init() of the application delegate should work just as well.