Value of optional type CGFloat not unwrapped error in Swift

后端 未结 1 547
小蘑菇
小蘑菇 2020-12-10 04:33

Code:

var loadView = UIView(frame: CGRectMake(0, 0, self.window?.frame.size.width, self.window?.frame.size.height))

I try to create a UIVie

相关标签:
1条回答
  • 2020-12-10 05:01

    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.

    0 讨论(0)
提交回复
热议问题