简体   繁体   中英

Cannot assign to immutable expression of type ' String?'

Working with text from a table view here. I am running into issues with the second bit of code.

This works:

var objects:CKRecord!


override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

   Notes.text = objects.objectForKey("content") as? String

}

Yet this doesn't work:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    objects.objectForKey("content") as? String = Notes.text // problem line

}

Why not?

Found the solution:

@IBAction func Save(sender: AnyObject) {

   objects["content"] = Notes.text as? String
}

Your original attempt does not work because objects.objectForKey("content") as? String objects.objectForKey("content") as? String is an R-value : both the objects.objectForKey(_:) method and the as? operator return read-only values that you cannot assign to.

Your posted solution works because the [] operator returns an inout value for dictionaries, making objects["content"] an L-value .

See this Wikipedia article for an explanation of L-values and R-values.

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