Johnd
Johnd

Reputation: 624

How to save an entire array of Integers?

I need to save all of the data in an array of Integers. I am in Swift Playgrounds, I tried using UserDefaults to save them this to store in

let savedSugarArray = [UserDefaults.standard.integer(forKey: "sugarArray")]

This to place the data in savedSugarArray

UserDefaults.standard.setValue(sugarArray, forKey: "sugarArray")

Since I'm using Swift Playgrounds I think I'd rather not use core Data since it is so lengthy. Is there another way to do this? Thank you in advance.

Upvotes: 0

Views: 782

Answers (2)

zombie
zombie

Reputation: 5259

I think an extension can be really helpful here

extension UserDefaults {
   open func set(_ intArray: [Int], forKey defaultName: String) {
      let array: NSArray = intArray as NSArray
      set(array, forKey: defaultName)
   }

   func intArray(forKey defaultName: String) -> [Int] {
      var result: [Int] = []

      let found = value(forKey: defaultName) as? NSArray ?? []

      found.forEach {
         guard let item = $0 as? Int else {
            return
         }
         result.append(item)
      }

      return result
   }
}

Usage:

UserDefaults.standard.set([1,2,3,4,5], forKey: "sugarArray")
UserDefaults.standard.synchronize()

let sugarArray = UserDefaults.standard.intArray(forKey: "sugarArray")

Little explanation

the array of Int is converted to an object of NSArray and then saved to the UserDefaults

to get the array we get an object and try to parse it as NSArray then we convert each item in the found array to an Int

then return the result

Upvotes: 0

JB288
JB288

Reputation: 96

UserDefaults doesn't function the same in playground (Xcode 8.2.1) as it does in a project. Normally, you'd use the following:

Set:

let integerArray: [Int] = [1,2,3,4,5]
UserDefaults.standard.set(integerArray, forKey: "sugarArray")

Get:

if let integerArray = UserDefaults.standard.object(forKey: "sugarArray") as? [Int]{
      //good to go
}
else{
     //no object for key "sugarArray" or object couldn't be converted to [Int]
}

However, to show that UserDefaults don't function the same in playground, simply copy this into your playground:

let integerArray: [Int] = [1,2,3,4,5]
UserDefaults.standard.set(integerArray, forKey: "sugarArray")
if let integerArray = UserDefaults.standard.object(forKey: "sugarArray") as? [Int]{
    print("UserDefaults work in playground")
}
else{
    print("UserDefaults do not work in playground")
}

Upvotes: 1

Related Questions