How can I use variables inside the key of a NSUserDefault? - iphone

Is it possible to insert a variable in the key of a NSUserDefault?
for example:
NSUserDefault.setInteger(10, forKey: "number /(var)")
I just tried a random syntax, just to make you understand.

Yes thats possible:
NSUserDefaults.standardUserDefaults().setInteger(10, forKey: "number \(temp)")
here "number \(temp)" is a complete string.
You can try this way to conform:
let temp = 10
NSUserDefaults.standardUserDefaults().setInteger(10, forKey: "number \(temp)")
print(NSUserDefaults.standardUserDefaults().objectForKey("number \(temp)"))
Which will print Optional(10)

Related

Swift: Get max value for key in array of dictionaries

I have an array containing dictionaries.
let arr = [["test":1], ["test":2], ["test":3], ["test":4]]
I now need to get the one dictionary that contains the highest value for the key "test" (without iterating through everything). I was thinking about filter(_:) but this will only filter out. map(_:) also does not work as I need to filter and not to map.
There's an example how to get the key with the highest value in a dictionary but this does not work in this case.
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
Any help is appreciated!
You can use max much like in your example.
let arr = [["test":1], ["test":4], ["test":3], ["test":2]]
print(arr.max { $0["test"]! < $1["test"]! })
This gives the dictionary with the highest value.
Of course the use of ! is bad unless it is guaranteed that each dictionary really has a "text" key.
Also note that using max will still result in the entire array being iterated. You can't avoid that unless your dictionaries are always sorted by the value. Then in that case simply use last instead of max.

Combining map with split

From having following string: 12#17#15 I want to get an array with the numbers: [12, 17, 15].
I've tried following approach, but firstly I still get an error (Cannot convert value of type '[Double?]' to expected argument type 'Double?'), and obviously, I prefer to do it all on one map instead of such chain. Why do these types differ..? I'd say they should be matching...
let substrings = records?.split(separator: "#", maxSplits: Int.max, omittingEmptySubsequences: true).map(String.init).map(Double.init)
let objects = substrings.map {value in Model(value: value ?? 0)}
Unless there's some technique I've never heard of, you're not using map correctly.
Here's an example of the code you want:
let string = "12#17#15"
let objects = string.split(separator: "#").map {Double($0) ?? 0}
in Swift, map does something to every entry of an array, and then results in some sort of output. What's going on here is that first just doing a simple split (I'm going to assume you don't actually need the upper limit of an Int for the max results, but you can re-add that if you wish), and then initing a Double with each substring (which you call with $0). If trying to create that Double fails, then I'm coalescing it to a 0 instead of a nil.
If you don't want the Doubles that fail and return nil to be zero, then use flatmap {$0} instead
I would use flatMap instead of map, as Double init with String can return optional.
let records = "12#17#15"
let substrings = records.split(separator: "#").flatMap {Double($0)}
print(substrings) // [12.0, 17.0, 15.0]

Simple decryption in swift with key & dictionary?

looking for a push in the right direction on a minor non problem but more curiosity driven search.
I'm trying to take a ton of text which has been "encrypted" with a plain as day key using uppercase, lowercase & numbers.
ie.
Array('1'=>'h', '0'=>'L', '3'=>'H',....
Stumbling around my brain trying to think if there was a way to build a dictionary with the value / key as has ben provided can I enter the encrypted text and reference the dictionary for the answer to output decrypted text?
Assuming the mapping is 1:1, ie, 1 character maps to 1 character, ie no numbers are greater than 9. This should work:
let cypher = ["1": "h",
"0": "L"] as [Character: Character]
//Add more here as needed.
let yourText = "014"
let decypheredText = yourText.map { char in
return cypher[char] ?? "?" //Untranslatable things mpa to ?
}.joined()

storing Int in swift 2

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

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
}