-1

I've stored data sent back by delegate as a user default and I'm trying to prepare it to send in a segue. I am able to send it in a segue, the problem I'm having is the data comes out in the form "optional[Data]" I know what optional means, but it doesn't let me unwrap UserDefault like an optional, even though it says it is optional?

Here's the code:

 func DataToPass(ArrayName: [String]) {
    print("Check ArrayContent--->",ArrayName)
    var DCollect = [String]()
    var CCollect = [String]()
    DCollect.append(ArrayName[0])
    CCollect.append(ArrayName[1])
    let defaults = UserDefaults.standard
    if let unwrap = defaults{
        unwrap.set(DCollect, forKey: "DCollect")
        unwrap.set(CCollect, forKey: "CCollect")
    }
}

The error is:

"Initializer for conditional binding must have Optional type, not 'UserDefaults'" on line if let unwrap = defaults{

Why can't I unwrap it like this?

Another Attempt:

    func DataToPass(ArrayName: [String]) {
        print("Check",ArrayName)
        UserDefaults.standard.set(ArrayName, forKey: "ToCollect")
        }


     override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if segue.identifier == "SegueInfo"{
        let firstController = segue.destination as! ViewController
        if let Tosend = UserDefaults.standard.value(forKey: 
        "ToCollect") as? String {
        Collect.append(Tosend)
        }
        firstController.AllData = Collect
            }

Nothing is appended this way, Tosend is empty?

Dan.code
  • 431
  • 2
  • 14
  • 4
    That makes no sense. `UserDefaults.standard` is the UserDefaults instance and not an optional. – Martin R Jun 29 '17 at 08:33
  • The field `standard` in user defaults is declared as `class var standard: UserDefaults { get }`. As you can see, it is not optional, and thus cannot be unwrapped – crizzis Jun 29 '17 at 08:33
  • 1
    `UserDefaults.standard` is not optional. You don't need to unwrap it. The error message tells you this. – Fogmeister Jun 29 '17 at 08:33

4 Answers4

2

To save something to user defaults:

UserDefaults.standard.set("It is a string", forKey: "meaningfulIdentifier")

To get something out from user defaults:

if let anyString = UserDefaults.standard.value(forKey: "meaningfulIdentifier") as? String {
    // Do something with anyString
}


You only need optional binding when you are dealing with getting something out from user defaults. For the data part you need this optional binding, not the User Defaults itself.

nayem
  • 7,285
  • 1
  • 33
  • 51
1

Why does it tell me that I can't unwrap UserDefaults?

The error message is trying to explain to you that UserDefaults.standard is not of an Optional type. That means that it is not of type Optional<UserDefaults>, which means it can't use the if-let statement to unwrap it.

What you want to unwrap is not the UserDefaults object which is already provided as a singleton through the UserDefaults.standard property.

What can I unwrap?

What you want to unwrap are the variables you are trying to retrieve.

Those would be the optional types you'll have to deal with. It is Optional because it may already exist in the UserDefaults or it may not yet exist.

How do I retrieve a string array that I stored into UserDefaults?

Using the key DCollect, use the appropriate method (i.e. stringArray(forKey:) to retrieve it.

let defaults = UserDefaults.standard

if let dcollect = defaults.stringArray(forKey: "DCollect") {
   // it already exists; now use the dcollect variable
} else {
   // it does not exist; do something (i.e. add dcollect value?) if it does not exist yet
}

How do I store a string array into UserDefaults?

let defaults = UserDefaults.standard
let value : [String] = ["My", "Very", "Eager", "Pluto"]
standard.set(value, forKey: "DCollect")
dsapalo
  • 1,819
  • 2
  • 19
  • 37
0

I am not sure why you are trying to unwrap UserDefaults.standard because you don't need to. It is not an optional, therefore you get error from Xcode.

You can straight add the values to the de UserDefaults like this:

let u = UserDefaults.standard u.set(["a", "b", "c"], forKey: "yourKey")

Jose Enrique
  • 59
  • 1
  • 4
  • Im only trying to unwrap it because when I print it, it comes out like this: `"Optional[data]"` and I want it just as a string, like this `"data"` – Dan.code Jun 29 '17 at 08:52
0

First, don't forget to import Foundation

Then try this code

func DataToPass(ArrayName: [String]) {
    UserDefaults.standard.set(ArrayName, forKey: "ToCollect")
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?){
    if segue.identifier == "SegueInfo"{
        let firstController = segue.destination as! ViewController
        if let Tosend = UserDefaults.standard.stringArray(forKey: "ToCollect") as? [String] {
            Collect += Tosend
        }
        firstController.AllData = Collect
    }
}
Fangming
  • 24,551
  • 6
  • 100
  • 90