-1

When I retrieve a value from core data, it is displaying with prefix "Optional" on the story board. How to avoid showing "Optional" in front of the retrieved value?

Here is the line of code:

schoolYearStartDateText.text = String(newRateMaster.schoolYearStartDate)

value entered - 01/01/11

Value displayed on debugger and Storyboard:

Optional(0011-01-01 04:56:02 +0000)

With NSSet this gets worse. Value prefixed with Optional and multiple levels of parenthesis!

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
RedMac
  • 1
  • 1
  • Put "!" at the end of it to unwrap the optional value. Read this https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html – boidkan Dec 08 '15 at 21:57
  • 1
    So basically something like this: `schoolYearStartDateText.text = String(newRateMaster.schoolYearStartDate)!`. You should read the documentation. – boidkan Dec 08 '15 at 22:04
  • 1
    Possible duplicate of [swift How to remove optional String Character](http://stackoverflow.com/questions/26347777/swift-how-to-remove-optional-string-character) – boidkan Dec 08 '15 at 22:10

1 Answers1

0

This is really a question about Swift optionals, and is nothing to do with Core Data. "Optional" shows up because you're using an optional variable. It's optional because it just might be nil, and that's how Swift handles that situation.

Using "!" will unwrap it but isn't really safe. If the value is nil and you're using "!", your app will crash.

You should probably use something like:

schoolYearStartDateText.text = String(newRateMaster.schoolYearStartDate) ?? ""

That will unwrap a non-nil optional safely, and use an empty string if the result is nil. And, you should read up on Swift Optionals to better understand what's going on.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170