0

Is it normal to get an extra "Optional("")" on the strings i am fetching in Core Data?

Here is the code

bowtie.name = "My bow tie"
bowtie.lastWorn = NSDate()

And this is what i am getting in the xcode output log.

Name: Optional("My bow tie"), Worn: Optional(2015-11-08 14:23:11 +0000)

Is there a way to get rid of the Optional("") thing?

1 Answers1

2

Every time you force unwrap an Optional (using !) a kitten dies.

There are several safe ways of unwrapping an Optional such as using if let or flatMap (even though it's not a real flatMap).

In several cases you can use Optional Chaining so you don't have to deal with Optionals before you actually have to. The null coalescing operator (??) is also pretty useful.

This SO answer is extremely helpful, you should definitely check it out.

If you want to fully understand the concept of Optionals take a look at the docs.

In that specific case, though, I'd recommend using something like let fetchedName = bowtie.name ?? "" (or any other fallback string that makes sense for your problem). When you force unwrap and for some bizarre reason the value is nil the app will crash. Nobody likes crashes, right?

Community
  • 1
  • 1
fpg1503
  • 7,492
  • 6
  • 29
  • 49