将核心数据中的值重新转换为文本字段

时间:2015-12-08 21:50:33

标签: swift core-data

当我从核心数据中检索一个值时,它会在故事板上显示前缀“Optional”。如何避免在检索到的值前面显示“可选”?

以下是代码行:

schoolYearStartDateText.text = String(newRateMaster.schoolYearStartDate)

输入的值 - 01/01/11

调试器和故事板上显示的值:

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

使用NSSet会变得更糟。前缀为可选和多个括号级别的值!

1 个答案:

答案 0 :(得分: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.