-3

The code:

class man: human {
    var ie = "ie/1/3/1///"
    let pe = "pe/1/3/3///"
    let ol = "ol/1/1/1///"
    let sejong = "sejong/3/1/1///"
    let gong = "gong/1/1/1///"
    let mans = [ie, pe, ol, sejong, gong]
}

The error:

Col 15: cannot use instance member 'ie' within property initializer; property initializers run before 'self' is available

How can I debug this?

aaron
  • 39,695
  • 6
  • 46
  • 102
김지훈
  • 11
  • 1
  • 1
  • @Abhijeetk431: thanks for wanting to improve this question. We don't add salutations here (hi, hello, etc) so it would be good if you did not add them in. Thanks! – halfer Nov 29 '17 at 11:14

1 Answers1

3

Instance variables cannot be used upon non-lazy initialization of each other.

Consider your code taking into account the following thing: it doesn't matter in which order you define and initialize a variable. From your (developer) perspective, they will all get initialized simultaneously (they are, of course, not from low-level perspective).

It means that when you write:

let mans = [ie,pe,ol,sejong,gong]  

You basically tell compiler to make up an array of something not yet initialized. None of the constituents of your array are existent when you make this assignment.

Common solution is to make your initialization - that which relies on other instance variables - lazy:

class man {
    var ie = "ie/1/3/1///"
    let pe = "pe/1/3/3///"
    let ol = "ol/1/1/1///"
    let sejong = "sejong/3/1/1///"
    let gong = "gong/1/1/1///"
    lazy var mans : [String] = {
         [ie,pe,ol,sejong,gong]
    }()
}

Unlike ordinary, lazy variable obtains its value on first use of this variable, but not instantly once an object has been created. You tell compiler: I don't mean to make up an array right away, but make me one when I firstly use this variable, after the object has already been created:

let theMan = man()

On this stage, theMan.mans property is not yet initialized. However, suffice it to perform even basic operation, like printing:

print(theMan.mans)

that this property is initialized. This is called lazy initialization and this is the way you can make up an array consisting of other instance variables upon initialization. Of course, you should remember that any dependent data may be modified and affect the init.

Hexfire
  • 5,945
  • 8
  • 32
  • 42