"Unable to assign the result of this expression" - How to set the property of an optional variable

I have a question regarding Swift and additional properties.

Suppose I have the following code:

import Foundation

class MyClass: NSObject {

    var parent: MyClass?
    var string: String?

    init() {
        super.init()

    }

}

let variable : MyClass = MyClass()
variable.string = "variable"
variable.parent?.string = "parent"

I get an error in the following line: "Unable to assign the result of this expression"

variable.parent?.string = "parent"

Now I can suppress this error by replacing the question mark with an exclamation mark, which, as far as I know, will force Swift to assume that the object will be at run time, but it will work because, obviously, there is no object.

Essentially, how can I set a property on an optional variable without doing something like "if variable.parent"?

+4
source share
2

string parent. , . , parent (, init()), if variable.parent ( ), assignParentString(), .

func assignParentString (string: String) {
  if let parent = self.parent {
    parent.string = string
  }
}

:

  3> class MyClass {
  4.     var parent : MyClass?
  5.     var name   : String?
  6.     func aps (name:String) {
  7.         if let parent = self.parent {
  8.             parent.name = name
  9.         }   
 10.     }   
 11. }   
 12> var mc = MyClass()
mc: MyClass = {
  parent = nil
  name = nil
}
 13> mc.name = "mc"
 14> mc.aps ("mcp")           // no error, name did not take
 15> mc
$R3: MyClass = {
  parent = nil
  name = "mc"
}
 16> mc.parent = MyClass()
 17> mc.aps ("mcp")
 18> mc
$R6: MyClass = {
  parent = Some {
    parent = nil
    name = "mcp"
  }
  name = "mc"
}
+1

,

let variable : MyClass = MyClass()
variable.string = "variable"
variable.parent = MyClass()
if let a = variable.parent {
   a.string = "parent"
}

, ,

variable.parent!.string = "parent"

, , .

+2

Source: https://habr.com/ru/post/1543243/


All Articles