1

I am new to Swift and am trying to compare my Error description name with different String constants to show the user different results, based on the error.

I am using:

let errorName = errors.first?["name"].debugDescription

The value of errorName comes as "Optional(AlreadyActiveUser)" and when i compare this to my constant string "AlreadyActiveUser", i get false.

I have tried many things, but i am not able to get the value of the string inside the optional.

Someone, please help.

Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Manvendra Sah
  • 103
  • 1
  • 10
  • You need to learn about "unwrapping". That's the key word of the concept you are looking for. – Larme Jul 03 '18 at 07:20
  • Possible duplicate of [What is an "unwrapped value" in Swift?](https://stackoverflow.com/questions/24034483/what-is-an-unwrapped-value-in-swift) – Larme Jul 03 '18 at 07:28

3 Answers3

2

You can use optional binding in this case...

guard let errorName = errors.first?["name"].debugDescription as? String {

    print("value is not present...")
    return
}

print(errorName)
//here you can compare errorName == "AlreadyActiveUser"
Mahendra
  • 8,448
  • 3
  • 33
  • 56
0

you can use this

if let errorName = errors.first?["name"] as? String {

 print(errorName)
//here you can compare errorName == "AlreadyActiveUser"

}
else
{
       print("value is not present...")
}
Devil Decoder
  • 966
  • 1
  • 10
  • 26
  • This looks like the correct answer, but *explaining* it would make it even better! – Why does OP's code not work, but your's does? – Martin R Jul 03 '18 at 07:13
  • because .debugDescription returns string and you are wrapping it again and i am not doing it so – Devil Decoder Jul 03 '18 at 07:30
0

try let errorName = errors.first!["name"].debugDescription

Notes that I forced wrapping first with ! instead of ?.

ahagbani
  • 122
  • 1
  • 8
  • Also, keep in mind that this will crash your app if the errors array is empty because it doesn't contain any element to have a first. So, it's better to use a guard statement of an if statement to assure that your app won't crash, – ahagbani Jul 03 '18 at 07:44