Search code examples
swiftcrasharkituserdefaultsscnvector3

Save value of SCNVector3 with UserDefaults in Swift


I am trying to save and load an SCNVector3, this is the code that I use to save and load the vector:

//Definition of the two vectors
let storedVector = SNCVector3Make(0,0,0)
let vector = SNCVector3Make(1,1,1)

let defaults = UserDefaults.standard

//Saving the vector
defaults.set(vector, forKey: "storedVector")

//Loading the vector into storedVector variable if already saved
let storedVector = defaults.object(forKey: "storedVector") as? SCNVector3 ?? storedVector

I have to check if the value is already saved because I save the value at the press of a button and load it when the application is loaded.

The problem is that the app is crashing when saving the vector.
However, if I divide the vector into three floats like this:

defaults.set(vector.x, forKey: "storedVectorx")
defaults.set(vector.y, forKey: "storedVectory")
defaults.set(vector.z, forKey: "storedVectorz")

and then load them like this:

storedVector.x = defaults.float(forKey: "storedVectorx")
storedVector.y = defaults.float(forKey: "storedVectory")
storedVector.z = defaults.float(forKey: "storedVectorz")

the app doesn't crash.

Can I save the vector without the app crashing and without dividing it into 3 floats?


Solution

  • You cannot save an SCNVector3 object directly to UserDefaults. For a shorter solution, you could save the vector values as an array or a dictionary.

    let vectorArray = [vector.x, vector.y, vector.z]
    UserDefaults.standard.set(vectorArray, forKey: "storedVector")
    

    let vectorDict = ["x": vector.x, "y": vector.y, "z": vector.z]
    UserDefaults.standard.set(vectorDict, forKey: "storedVector")