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...
@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.
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.
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.
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.
First of all get to know, what is actually !
and ?
?
: if the value can become nil in the future, so that you test for this.!
: 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With