Home > Mobile >  About the Swift always use a instance member & # x27; MainW & # x27; Within the property, initialize
About the Swift always use a instance member & # x27; MainW & # x27; Within the property, initialize

Time:10-07

Does the iOS before, for the first time contact Swift, when writing a small Demo encounter a problem
I wrote two global variables, to obtain the width of the screen is high, at first in the class class, but not in the viewDidLoad, then I created a control in viewDidLoad, to use the high width is no problem, later found out that the control need in other ways, put the viewDidLoad controls mentioned, this is the Bug appears as title
The code is as follows:
 
The class ViewController: UIViewController, UISearchBarDelegate {

Let mainW: CGFloat=UIScreen. Main. Bounds. Width
Let mainH: CGFloat=UIScreen. Main. Bounds. Height
Let the searchBar: UISearchBar=UISearchBar. Init (frame: CGRect (x: 20, y: 100, width: mainW - 40, height: 50))

Override func viewDidLoad () {
Super viewDidLoad ()

SearchBar. Placeholder="please enter the keyword"
SearchBar. Text="I have a horrible house"
}
}

The bug description:
 
Always use a instance member 'mainW' within the property, initializer. The property initializers run before the 'self' is


Then I put the wide high in class and outside
 
Let mainW: CGFloat=UIScreen. Main. Bounds. Width
Let mainH: CGFloat=UIScreen. Main. Bounds. Height

The class ViewController: UIViewController, UISearchBarDelegate {

Let the searchBar: UISearchBar=UISearchBar. Init (frame: CGRect (x: 20, y: 100, width: mainW - 40, height: 50))

Override func viewDidLoad () {
Super viewDidLoad ()

SearchBar. Placeholder="please enter the keyword"
SearchBar. Text="I have a horrible house"
}
}

Here I want to ask me this two wide high cannot be placed in the class?

CodePudding user response:

Wide high let you convert into lazy var