[英]Swift 3 Optional being appended to String
I save a value from a textview to coredata like so 我像这样将文本视图中的值保存到coredata
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newAttr = NSEntityDescription.insertNewObject(forEntityName: "TableName", into: context )
let attribute_name = textView.text
newAttr.setValue(attribute_name, forKey "attr_name")
context.save()
Then I try to read it back like so: 然后,我尝试像这样将其读回:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest = TableName.fetchRequest()
let cdRowsArr = try context.fetch(fetchRequest)
let cdRow = cdRows[0]
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name"))
let attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize:15)]
let boldString = NSMutableAttributedStrign(string: txtViewDesc, attributes: attrs)
textView.attributedText = boldString
And for some reason, every time, the output is Optional("originalTextValue") or nil, if it's empty 并且由于某种原因,每次输出都是Optional(“ originalTextValue”)或nil(如果为空)
I don't understand why the value I want is surrounded by optional 我不明白为什么我想要的值被可选的包围
Its because the var will be declared as optional. 这是因为var将被声明为可选。 Use this code for your accessing value of your variable.
使用此代码作为变量的访问值。
if let value = originalTextValue{
//use value here now it wont be optional.
print(value)
}
Replace this line: 替换此行:
let attribute_name = textView.text
with this: 有了这个:
let attribute_name = textView.text ?? ""
It should solve this optional issue. 它应该解决此可选问题。 If it still doesn't work then replace this line as well:
如果仍然无法正常工作,则也替换此行:
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name"))
with: 与:
let txtViewDesc = String(describing: cdRow.value(forKey: "attr_name") ?? "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.