-2
let l1 = Lekarz(imie: "Jan", nazwisko: "Kowalski", specjalnosc: "Dermatolog", dzienPracy: DzienPracy(dzien: .PN, godzinaPocz: .osiem, godzinaKon: .dziewiec))
let l2 = Lekarz(imie: "Adrian", nazwisko: "Nowakowski", specjalnosc: "Endokrynolog", dzienPracy: DzienPracy(dzien: .WT, godzinaPocz: .jedenascie, godzinaKon: .czternascie))
let l3 = Lekarz(imie: "Hubert", nazwisko: "Zieliński", specjalnosc: "Logopeda", dzienPracy: DzienPracy(dzien: .PT, godzinaPocz: .pietnascie, godzinaKon: .szesnascie))


let lekarze = [l1, l2, l3]

When i try to declare an array i get an error like this "Cannot use instance member 'l1' within property initializer; property initializers run before 'self' is available".

iX0ness
  • 123
  • 9
  • You should move this into viewDidLoad or in a other function – J. Doe Aug 02 '17 at 11:43
  • As a dirty fix (referring to this probably being an XY problem) you could let `lekarze` be a lazy var, and explicitly annotate `self` when accessing the `l1`, ..., properties. E.g. `lazy var lekarze: [Lekarz] = [self.l1, self.l2, self.l3]`. – dfrib Aug 02 '17 at 11:44
  • See https://stackoverflow.com/questions/25855137/viewcontroller-type-does-not-have-a-member-named or https://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other – Martin R Aug 02 '17 at 11:45

1 Answers1

1

As the error message mentions, one instance variable can't refer to another before the class is finished being created.

For your case, if Lakarz is a struct then the values of l1, l2, and l3 are fixed at compile time. A workaround is to declare l1, l2, and l3 as static so that they aren't instance members:

class Foo {
    static let l1 = Lekarz(imie: "Jan", nazwisko: "Kowalski", specjalnosc: "Dermatolog", dzienPracy: DzienPracy(dzien: .PN, godzinaPocz: .osiem, godzinaKon: .dziewiec))
    static let l2 = Lekarz(imie: "Adrian", nazwisko: "Nowakowski", specjalnosc: "Endokrynolog", dzienPracy: DzienPracy(dzien: .WT, godzinaPocz: .jedenascie, godzinaKon: .czternascie))
    static let l3 = Lekarz(imie: "Hubert", nazwisko: "Zieliński", specjalnosc: "Logopeda", dzienPracy: DzienPracy(dzien: .PT, godzinaPocz: .pietnascie, godzinaKon: .szesnascie))


    let lekarze = [Foo.l1, Foo.l2, Foo.l3]
}
vacawama
  • 150,663
  • 30
  • 266
  • 294