可选类型 CGFloat 的值未在 Swift 中解开错误 [英] Value of optional type CGFloat not unwrapped error in Swift
问题描述
代码:
var loadView = UIView(frame: CGRectMake(0, 0, self.window?.frame.size.width, self.window?.frame.size.height))
我尝试以编程方式创建一个 UIView.当尝试为视图设置窗口高度和宽度时,它给出的错误是可选类型 'CGFloat 的值?'未解开;您是想使用!"吗?或者 '?'?"为什么显示此错误?任何帮助将不胜感激.提前致谢
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
推荐答案
您正在使用 可选链,这意味着 self.window?.frame.width
计算为有效整数,如果 window
不是 nil
,否则计算结果为 nil
- height
相同.
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
.
因为你不能创建一个包含 nil
的 CGRect
(或者更好的说法,CGRectMake
不接受它的任何参数的可选项),编译器将其报告为错误.
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.
解决方案是隐式解包self.window
:
var loadView = UIView(frame: CGRectMake(0, 0, self.window!.frame.size.width, self.window!.frame.size.height))
但是,如果 self.window
是 nil
,则会引发运行时错误.用可选绑定包围它总是更好的做法:
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
}
这样你就可以确定只有在 self.window
实际上不是 nil 时才会创建视图.
so that you are sure the view is created only if self.window
is actually not nil.
这篇关于可选类型 CGFloat 的值未在 Swift 中解开错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!