0

Please see the code below:

class myViewMgr {
    var myView: UIView?

    func create() {
        myView = UIView()
        myView!.translatesAutoresizingMaskIntoConstraints = false
        myView!.backgroundColor = UIColor.blackColor()
        myView!...
        myView!...
    }
}

I have a class and a variable myView which might be empty. Inside create(), I create an instance for it and start using it. And I have to force unwrapping myView in the following code.

I am wondering if I am doing something wrong in some general Swift concept? Any advise to help me and correct me is appreciated.

Joe Huang
  • 6,296
  • 7
  • 48
  • 81

3 Answers3

2

You would work around it by doing

let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
...
myView = view

But if you do use the attribute, then yes, you will need to force unwrap it every single time.

Christian Schnorr
  • 10,768
  • 8
  • 48
  • 83
0

Better yet, if you are sure that myView is never going to be nil once you invoke create() on it, it is better to declare myView as an implicitely unwrapped variable:

var myView: UIView!

And then after the Create() called, you can use myView as any other variable without needing to forced unwrapping etc.

Shripada
  • 6,296
  • 1
  • 30
  • 30
0

You will need to do this way because you declare a type called "Optional UIView". That's why you always need to use ! to unwrap it. If you are sure that view is always there. You can just declare it as UIView. Then, it's just like how you use it in other normal programming language.

We have great explanation in this platform. You should make decision after understand what it actually is: What is an optional value in Swift?

Community
  • 1
  • 1
Lucas Huang
  • 3,998
  • 3
  • 20
  • 29