sadhu_sanjay
sadhu_sanjay

Reputation: 33

User Default is passing nil check and giving me random Byte number

if UserDefaults.standard.object(forKey: "noti") != nil {
    print("print ", UserDefaults.standard.value(forKey: "noti") as Any)
}

that “noti” key is nil but it is still passing nil check and printing this:

print Optional(<62706c69 73743030 d4010203 0405080a 0b542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976 6572d106 0754726f 6f748000 a1095524 6e756c6c 12000186 a05f100f 4e534b65 79656441 72636869 76657208 11161f28 32353a3c 3e444900 00000000 00010100 00000000 00000c00 00000000 00000000 00000000 00005b>)

I don't understand why it's passing nil check when the value is nil

Upvotes: 0

Views: 220

Answers (2)

Matt
Matt

Reputation: 1761

I tried your code but it is successfully skipping out of if condition. Are you sure you did not added anything to it before at any time.

Try Swift's way of checking for nil values

if let noti = UserDefaults.standard.object(forKey: "noti") {
   // 'noti' is available
} else {
   // 'noti' is not available 
}

If that did not work out, try removing 'noti' from UserDefault before if condition

UserDefault.standard.removeObject(forKey: "noti")

if let noti = UserDefaults.standard.object(forKey: "noti") {
   // 'noti' is available
} else {
   // 'noti' is not available 
}

Upvotes: 0

tomahh
tomahh

Reputation: 13661

The print statement makes it obvious that the "noti" key has a value. It's data value is in this case :

<62706c69 73743030 d4010203 0405080a 0b542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976 6572d106 0754726f 6f748000 a1095524 6e756c6c 12000186 a05f100f 4e534b65 79656441 72636869 76657208 11161f28 32353a3c 3e444900 00000000 00010100 00000000 00000c00 00000000 00000000 00000000 00005b>


Usually, if you are to use an optional after checking if it's nil, you will want to use the if let construct

if let noti = UserDefaults.standard.object(forKey: "noti") {
  // Here, noti will be of type Any, rather than Optional<Any>
} else {
  // noti was nil, no need to have any reference to it
}

Upvotes: 2

Related Questions