斯威夫特:'!'的差异和'?'在迅速 [英] Swift : Difference in '!' and '?' in swift

查看:163
本文介绍了斯威夫特:'!'的差异和'?'在迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面声明:

@IBOutlet var hw_label : UILabel!

如果我上面写的比它成功运行,

If I write as above than it's running successfully,

但是当我声明如下:

    @IBOutlet var hw_label : UILabel!

              and 
    hw_label.text = "Hello World"

它显示错误为图像。

I只是想知道'!'和'?'之间有什么区别。

I Just want to know that what is the difference between '!' and '?'.

或为什么我们必须使用它??

or why we have to use this..?

推荐答案

Swift中有两种类型的变量。

There are two types of variables in Swift.


  1. 可选变量

  2. 正常(非可选)变量

可选变量:
最短描述是可选变量/对象包含属性object-returns-nil-when-non-exist。在objC中,我们创建的几乎所有对象都只是可选变量。也就是说,对象具有属性object-returns-nil-when-non-exist行为。但是,这种特殊行为并不是一直需要的。因此,为了识别选项,使用符号'?'和'!'。同样有两种类型的期权...

Optional Variables: The shortest description is Optional variables/objects contains the the property "object-returns-nil-when-non-exist". In objC almost all the object we create is optional variable only. That is the objects has the property "object-returns-nil-when-non-exist" behavior. However, this particular behavior is not needed all the time. So, to identify the optionals the symbols '?' and '!' has been used. Again there are two type of optionals...


  • 正常期权(?)

  • 隐式解包期权(!)

正常期权:

var normalOptional : String?

隐式解包期权:

var specialOptional : String!

两者都有可选行为,但区别在于隐式解包可选也可以用作普通(非可选)值。

Both are having the "optional" behaviour, but the difference is the 'Implicitly unwrapped optional' can also be used as a normal(non-optional) value.

例如,indexPath变量在函数(cellForRowAtIndex)参数列表中通过默认的tableview委托方法声明。调用cellForRowAtIndex时存在行值。在那里,indexPath变量在函数(cellForRowAtIndex)参数列表中声明。
因此,从'indexPath'展开'row'值如下所示。

For instance, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list by default tableview delegate methods. The row value exists when the cellForRowAtIndex is get called. There, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list. So, the unwrapping of 'row' value from 'indexPath' is as follows.

       var rowValue = indexPath?.row // variable rowValue inferred as optional Int value
       or
       var rowValue = indexPath!.row// variable rowValue inferred as normal Int value

注意:使用'时!'展开,必须非常肯定特定的类存在(包含值)。

Note: When using the '!' unwrapping, have to be very sure that the particular class exists(contains value).

希望这个链接能给你更多的想法。 可选变量/常量的预期用途是什么在swift

Hope this link will gives you more idea. What is the intended use of optional variable/constant in swift

这篇关于斯威夫特:'!'的差异和'?'在迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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