Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBOutlets and IBactions require ! in the end

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...

like image 973
Julian E. Avatar asked Dec 18 '14 08:12

Julian E.


People also ask

What is IBOutlet and IBAction?

@IBAction is similar to @IBOutlet , but goes the other way: @IBOutlet is a way of connecting code to storyboard layouts, and @IBAction is a way of making storyboard layouts trigger code. This method takes one parameter, called sender . It's of type UIButton because we know that's what will be calling the method.

Why are IBOutlets force unwrapped?

The reason many developers are not fond of optionals is because you cannot directly access the value of an optional. To safely access the value of an optional, you need to unwrap it. Optional binding is a construct that lets you safely access the optional's value.

Is it required to create IBOutlet and IBAction for each UI object in your project?

Every object you add in Interface Builder (i.e.buttons, labels, text, etc. ) must have an IBOutlet instance variable declared in the corresponding Xcode project. An IBOutlet helps connect the object control to the code to make the object accessible via the program.

What is the difference between IBOutlet and IBAction?

An IBOutlet is for hooking up a property to a view when designing your XIB. An IBAction is for hooking a method (action) up to a view when designing your XIB. An IBOutlet lets you reference the view from your controller code.


1 Answers

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
like image 84
virus Avatar answered Sep 18 '22 07:09

virus