Search code examples
iosswift

property initializers run before 'self' is available error Swift


I have a SearchURL String which gets a chose variable from previous view controller. And with this gotten variable, SearchURL should be used in callAlamo func. But I have an error:

enter image description here

Should I use async dispatch or something like this? I've tried many things like putting everything in viewDidLoad() but did not work. Anybody could help?


Solution

  • The viewDidLoad will not be called everytime you enter your view controller, as such, you may not detect updates to the chosed property (among other tricky issues).

    You could do it in viewWillAppear method instead:

    var SearchURL: String!
    
    overide func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        SearchURL = "...\(chosed!)..."
        ...
    }
    

    Or you could use a lazy variable:

    lazy var SearchURL = {
        return "...\(self.chosed!)..."
    }()
    

    Or use a computed property as suggested by Connor Neville below.