Code:
var loadView = UIView(frame: CGRectMake(0, 0, self.window?.frame.size.width, self.window?.frame.size.height))
I try to create a UIView progrmatically.when try to set window height and width for view it gives error as "Value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?" why this error showing?any help will be appreciated.thanks in advance
You are using optional chaining, which means that self.window?.frame.width
evaluates to a valid integer if window
is not nil
, otherwise it evaluates to nil
- same for height
.
Since you cannot make a CGRect
containing nil
(or better said, CGRectMake
doesn't accept an optional for any of its arguments), the compiler reports that as an error.
The solution is to implicitly unwrap self.window
:
var loadView = UIView(frame: CGRectMake(0, 0, self.window!.frame.size.width, self.window!.frame.size.height))
But that raises a runtime error in the event that self.window
is nil
. It's always a better practice to surround that with a optional binding:
if let window = self.window {
var loadView = UIView(frame: CGRectMake(0, 0, window.frame.size.width, window.frame.size.height))
.... do something with loadVIew
}
so that you are sure the view is created only if self.window
is actually not nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With