I am working on a new project in Swift and am having a tough time understand a particular use of optionals. I have declared a UIRefreshControl property for use in the class. I declared it as an optional.
var refreshControl : UIRefreshControl?
In the viewDidLoad() I first tried the following.
override func viewDidLoad()
{
super.viewDidLoad()
self.refreshControl!.addTarget(self, action: Selector("refreshInvoked:"), forControlEvents: UIControlEvents.ValueChanged)
self.feedsTableView.addSubview(self.refreshControl!)
}
The app crashed on
self.refreshControl!.addTarget(self, action: Selector("refreshInvoked:"), forControlEvents: UIControlEvents.ValueChanged
telling me the following. "fatal error: unexpectedly found nil while unwrapping an Optional value."
I realized that I had not instantiated the UIRefreshControl object so I tried the following to fix it.
override func viewDidLoad()
{
super.viewDidLoad()
self.refreshControl! = UIRefreshControl()
self.refreshControl!.addTarget(self, action: Selector("refreshInvoked:"), forControlEvents: UIControlEvents.ValueChanged)
self.feedsTableView.addSubview(self.refreshControl!)
}
To my surprise I received the same error message for
self.refreshControl! = UIRefreshControl()
When I remove the ! the error goes away and everything works.
self.refreshControl = UIRefreshControl()
Questions
Why don't we have to forcibly unwrap the optional when we instantiate it?
Would I be better off declaring the property as an implicitly unwrapped optional? If so why?
var refreshControl : UIRefreshControl!