Dan Dan - 1 year ago 47
Swift Question

Swift - Still printing "Optional" even after checking if object exists - how do I unwrap

Very new to Swift so a very simple problem here but I am struggling to unwrap an optional from a

stored value. The value for UID is "dan". Here's the code:

override func viewDidLoad() {

let uidObject1 = UserDefaults.standard.object(forKey: "UID")

if let uid = uidObject1 {
updateUsername.setTitle("\(uid)", for: UIControlState.normal)
print("on load \(uid)")

This changes the button updateUsername label and also prints to the console the following...

on load Optional("dan")

I cannot get rid of Optional(). I've tried to unwrap uid.

print("on load (uid!)")

as Xcode tells me I cannot force unwrap value of a non-optional type 'Any'.

From searching around I understood that checking -
if let uid = uidObject1
- removed the Optional() as it only runs if
exists. Can someone point me in the right direction?

Here is my set code;

@IBAction func updateUsername(_ sender: AnyObject) {
if let uid = userName.text {
UserDefaults.standard.set("\(userName.text)", forKey: "UID")
updateUsername.setTitle("\(uid)", for: UIControlState.normal)

ANSWER - Needed to unwrap the set (userName.text) like so > (userName.text!) SOLVED. Thanks Oliver.

Answer Source

I think when you set UID to UserDefaults you set the string using the same method you have used to print. However if you don't unwrap the optional at that point then the string is saved as "optional(Dan)". So you are unwrapping in the code above correctly but the string is already "optional(Dan)".

Eg your code to set the value of UID likely looks like this

UserDefaults.standard.setValue("\(name)", forKey: "UID")

But name is an optional. Unwrap name and your problem should be fixed.