Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of optional type CGFloat not unwrapped error in Swift

Tags:

swift

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

like image 829
user3823935 Avatar asked Sep 04 '14 10:09

user3823935


1 Answers

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.

like image 135
Antonio Avatar answered Sep 28 '22 17:09

Antonio