IBOutlets and IBactions require ! in the end

Julian E. picture Julian E. · Dec 18, 2014 · Viewed 14.3k times · Source

I tried to start and go from Obj-C to Swift today and I was reading the documentation. I tried to create an easy IBOutlet in Swift and it constantly gave me those errors.

View Controller has no initialiser

required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }

IBOutletproperty has non-optional type 'UILabel'

and that constantly pops up with this code:

@IBOutlet var outputLabel : UILabel

but when I add an ! mark, it's running without errors like so

@IBOutlet var outputLabel : UILabel!

Same thing happens for IBActions...

Answer

virus picture virus · Dec 18, 2014

First of all get to know, what is actually ! and ?

  • Use ? : if the value can become nil in the future, so that you test for this.
  • Use ! : if it really shouldn't become nil in the future, but it needs to be nil initially.

@IBOutlet:

When you declare an outlet in Swift, the compiler automatically converts the type to a weak implicitly unwrapped optional and assigns it an initial value of nil.

In effect, the compiler replaces @IBOutlet var name: Type with @IBOutlet weak var name: Type! = nil.

Xcode would change it and Force restrict on declare @IBOutlet non option type variable , so following both kind of declaration for @IBOutlet is Valid till date.

@IBOutlet var outputLabel : UILabel!
@IBOutlet var priceLabel : UILabel?

However, if you control drag an outlet for a label in beta 4 this happens:

@IBOutlet var priceLabel : UILabel! = nil