IBOutlets和IBactions需要!到底 [英] IBOutlets and IBactions require ! in the end

查看:270
本文介绍了IBOutlets和IBactions需要!到底的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天试图从Obj-C开始到Swift,我正在阅读文档。我试图在Swift中创建一个简单的IBOutlet,它经常给我这些错误。

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没有初始化


必需init(编码器aDecoder:NSCoder){
fatalError(init(编码器:)尚未实现)}

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

IBOutletproperty具有非可选类型'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!

同样的事情发生在IBActions ...

Same thing happens for IBActions...

推荐答案

首先要了解,什么是实际上

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:

当您在Swift中声明一个插座时,编译器会自动将类型转换为弱隐式解包可选并为其指定初始值 nil

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.

实际上,编译器替换 @IBOutlet var name:键入 @IBOutlet weak var name:输入! = nil

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

Xcode会更改它并强制限制声明 @IBOutlet 非选项类型变量,因此遵循 @IBOutlet 的两种声明都有效至日期。

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?

但是,如果您控制拖动beta 4标签的插座,则会发生这种情况: / strong>

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

@IBOutlet var priceLabel : UILabel! = nil

这篇关于IBOutlets和IBactions需要!到底的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆