Search code examples
arraysswiftswift-playground

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.


Solution

  • 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")
    }