You can save a number of simple variable types in the user defaults:
An NSNumber
is an NSObject
that can contain the original C style numeric types, which even include the C/Objective-C
style BOOL
type (that stores YES
or NO
). Thankfully for us, these are also bridged to Swift, so for a Swift program, an NSNumber
can automatically accept the following Swift types:
- UInt
- Int
- Float
- Double
- Bool
Dmitry Popov's answer in Quora
Remember how you were taught in school how to add numbers like 38 and 54. You work with separate digits. You take rightmost digits, 8 and 4, add them, get the digit 2 in answer and 1 carried because of an overflow. You take the second digits, 3 and 5, add them to get 8 and add the carried 1 to get result 9, so the whole answer becomes 92. A 32-bit processor does exactly the same, but instead of decimal digits it's got 32-bit integers, algorithms are the same: work on two 32-bit parts of 64-bit number separately, deal with overflows by carrying from lower to higher word. This takes several 32-bit instructions and the compiler is responsible to encode them properly.
Save Int64
to UserDefaults
import Foundation
let defaults = UserDefaults.standart
//Define an 64bit integer with `Int64`
let myInteger: Int64 = 1000000000000000
//Save the integer to `UserDefaults`
defaults.set(myInteger, forKey: "myIntegerKey")
// Get the saved value from `UserDefaults`
guard let savedInteger = defaults.object(forKey: "myIntegerKey") as? Int64 else { return }
print("my 64bit integer is:", savedInteger)
Save 64bit Int
to UserDefaults
via converting to String
let myInteger: Int64 = 1000000000000000
let myString = String(myInteger)
//Save the `myString` to `UserDefaults`
UserDefaults.standard.set(myString, forKey: "myIntegerKey")
// Get the value from `UserDefaults`
let myString = UserDefaults.standard.string(forKey: "myIntegerKey")
let myInteger = Int64(myString!)
Resources