storing Int in swift 2 - swift

I am new to swift so need some help. want to get a number from text field (which input by user) and sum it then store it for the next time. So when user come back in other time and input another number will be summed to the previous number.
let say, user input 10 and close the app then come back and input 5. the app will sum them and give 15 so on and so forth.
thanks for help

You can use NSUserDefault to save the value.
Example : https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-nsuserdefaults
Write :
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(10, forKey: "value")
Read :
let defaults = NSUserDefaults.standardUserDefaults()
let value = defaults.integerForKey("value")
You can also use code data : https://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started

many thanks for you all
I just found the best way. I just used this code
first read it:
let defaults = NSUserDefaults.standardUserDefaults()
let X = defaults.integerForKey("Cost")
convert the field.text! in to integer and add the previous value "X"
Cost = integer! + X
re-write the default
defaults.setValue(Cost, forKey: "Cost")
defaults.synchronize()
done

Related

How to contunally add to a number in SparkAR ( += equivalent)

New to reactive programming and pretty lost.
I have a number (which can be positive or negative) coming into a script from a patch in SparkAR and I'd like to add the number to itself once every frame.
ie if the incoming number is 1 and it comes in 9 times the variable would be 9.
let intoScript = Patches.getScalarValue('intoScript').pinLastValue;
let myValue = Reactive.add(myValue, intoScript);
The above doesnt work.
One way-
Increment counter in Patch editor and send variable value to SparkAR.
(https://sparkar.facebook.com/ar-studio/learn/documentation/docs/visual-programming/javascript-to-patch-bridging/)
let originalValue = Reactive.val(0)
function increment(newValue){
Diagnostics.watch('originalValue', originalValue)
originalValue = newValue.add(originalValue)
}
Don't forget to import Reactive module. more info about logical operations here

What's faster/should be rather used for short(ish) Strings: Split or Substring?

Swift 5, Xcode 10.
I'm looping through an array of Strings (size probably < 20), each of them looks something like this:
johnsmith.20190202102030.conf
janedoe.19700101115959.conf
I know the first part (the name) beforehand but want to extract the middle part (birthday: 8, 12 or 14 characters long).
Version 1:
let f = "johnsmith.20190202102030.conf"
let name = "johnsmith"
let start = f.index(f.startIndex, offsetBy: name.count+1)
let end = f.index(f.startIndex, offsetBy: f.count-5)
let birthday = String(f[start..<end])
Version 2:
let f = "johnsmith.20190202102030.conf"
let farr = f.split(separator: ".").map(String.init)
let birthday = farr[1]
I'm currently only doing this for 10 Strings and (of course) didn't notice any difference in speed. Even with 100 Strings there probably won't be much of a difference anyway but I'm curious:
Ignoring the length of the code and potential errors, is there a reason (apart from personal preference) to prefer using one version over the other (e.g. speed with 100k Strings - I'm not asking for actual measurements!)?
From my very rough testing, it seems that the substring version is faster. However, in your case I would opt for using the version using split. The code is much more readable to me.

Swift 4: How to compare doubles to another?

i have 3 Doubles, their values are random, and i am trying to achieve a comparison between them
so my code is
let double1 = 10.00 // notes: they're all random between 1-100 so i don't know what this will be
let double2 = 7.66
let double3 = 6.43
but, i tried
if (double1?.isLess(than: 50.0))! {
print("Low")
} else {
print("High")
}
but as i mentioned, this can't be done due to the random values, i need to compare two of them to each other, to make sure that one of them will be higher
Its actually rather very simple:
let maxDouble = max(max(double1, double2), double3) // prints 10

Saving UInt32 Values Into NSUserDefaults (Swift 2.0) error

I am very new to Swift 2.0 and am pretty stuck here...
I have created a random number generator based off a user set range for low and high limits. This function worked great with my test function when I could set the variables for low and high to Uint32
Once I tried to store the low/high range in NSUserDefaults as an integer. Now when I try to load the values set by the user for the low and high to use in my function below it gives me the error that it needs to be a UInt32 value.
The problem is.... I cannot seem to figure out how to save them in NSUser as that type. Or unwrap it as that type coming out of the UserDefaults.
My specific error message is...
ERROR IS Binary Operator + cannot be applied to operands of type UInt32 and In
Thanks so much ahead of time for your help and time I truly appreciate it! You guys are awesome here!
Let me know if there is anything else you need from me :)
//CREATE SAVE SETTINGS FOR LOW AND HIGH RANGE
NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange")
NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange")
//Variables to load in values from NSUserDefaults on load
var catLowRange = 0 //Load In Low Range From NSUser
var catHighRange = 40 //Load In High Range From NSUser
//LOAD IN VALUES TO VARIABLES FROM NSUSERDEFAULTS
catLowRange = NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange")
catHighRange = NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange")
**//My Function To Generate RandNumber...**
*ERROR IS Binary Operator + cannot be applied to operands of type UInt32 and Int*
randomNumber = arc4random_uniform (catHighRange - catLowRange) + catLowRange
For anyone wondering... Thanks to Adam we have an answer... Here is the code broken down how I used his suggestion to make this thing work :)
//WORKING METHOD!?
//vars for use
let catLowRange : UInt32 = 0
let catHighRange : UInt32 = 40
var randNumGenerated : UInt32 = 0
//SAVEPOINTS (STEP 1 - save the UInt32s as int for saving)
NSUserDefaults.standardUserDefaults().setInteger(Int(catLowRange), forKey: "CatLowRange")
NSUserDefaults.standardUserDefaults().setInteger(Int(catHighRange), forKey: "CatHighRange")
//LOAD (STEP 2 - Take Int save as a UInt32 now)
let catLowRangeLoad = UInt32(NSUserDefaults.standardUserDefaults().integerForKey("CatLowRange"))
let catHighRangeLoad = UInt32(NSUserDefaults.standardUserDefaults().integerForKey("CatHighRange"))
//FUNCTION TEST
randNumGenerated = arc4random_uniform (catHighRangeLoad - catLowRangeLoad) + catLowRangeLoad
//CHECK
print ("catLowRange = \(catLowRange)")
print ("catLowRangeLoad = \(catLowRangeLoad)")
print ("catHighRange = \(catHighRange)")
print ("catHighRangeLoad = \(catHighRangeLoad)")
print ("randNumGen = \(randNumGenerated)")
Use this code (updated for swift 3):
let number : UInt32 = 8
UserDefaults.standard.set(NSNumber(value: number), forKey: "key")
let number2 = (UserDefaults.standard.value(forKey: "key") as? NSNumber)?.uint32Value

Increment number in Dictionary

I have a Dictionary [String:AnyObject] which contains some keys and values.
I want to increment a key to which value is of type Double.
I can do it this way:
let nr = dict["number"] as! Double
dict["number"] = nr + 10
But I dont like that way so Im wondering if there is another way
I tried this:
(dict["number"] as! Double) += 10
But that gives me an error:
Binary operator '+=' cannot be applied to operands of type '(Double)' and 'Double'
Why isn't this working?
Following is an alternative. If you want to avoid force unwrapping an optional:
dict["number"] = (dict["number"] ?? 0) + 10
You are close and in fact you can write to a dictionary using +=, the problem is your cast. For example we can do:
var dict = ["number" : 2]
dict["number"]! += 10
and now dict["number"] returns 12. Now this is creating a new value (12) and replacing it into the dictionary, it is just a clean way of looking at it.
The problem with your code is that the left side (dict["number"] as! Double) gives you a Double. So you have say (12), then the right side is a Double too (10). So your code ends up looking like (12) += 10 which you can clearly see as problematic, since this is equivalent to 12 = 12 + 10, yikes!
So that being said, you can use the my first solution if you are working with native Swift dictionaries, otherwise your solved solution above works too, just a bit longer.
Lastly, if you are really looking for a one liner that works with your exact situation you should be able to do something like:
dict["number"] = (dict["number"] as! Double) + 10
Another option:
dict["number", default: 0] += 10
The safe way of casting would be:
if let num = dict["number"] as? Double {
dict["number"] = num + 10
}