简体   繁体   中英

Swift 3 Optional being appended to String

I save a value from a textview to coredata like so

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

I don't understand why the value I want is surrounded by optional

Its because the var will be declared as optional. 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") ?? "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM