Value of optional type CGFloat not unwrapped error in Swift

若如初见. 提交于 2019-11-27 03:20:53

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/25662595/value-of-optional-type-cgfloat-not-unwrapped-error-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!