在 swift 3.0 中使用 optional 和不使用 optional 声明非赋值变量有什么区别

What is the difference between using optional and not using optional to declare non assign variables in swift 3.0

我们可以在 swift 3.0

中像下面这样声明 nil 个变量
var aString : String?

然后我们可以这样赋值

aString = "hello"

那么如果我们 concatenate ,我们必须 cast 如下所示

var newone: String = aString! + " Whosebug"

But We can do the same thing like below and when we concatenate, we do not need to Unwrap. why is that

.

var bStirng : String

bStirng = "hello"
var newBString : String = bStirng + " StackOveflow"

使用optional的唯一好处是我们可以检查变量是否为nil

是的,就是这样。更多信息:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330

使用可选项有很多优点,是的,在我看来,主要优点是它迫使您每次都检查 nil 值。

但是,您以错误的方式使用了可选值(从您显示的代码来看)。你不只是说 "Ah the weather's good today, let me make this variable an optional!" 我认为这就是为什么你认为使用它们只有一个优势。

有时,只有将变量设为可选才有意义,因为变量的性质就是这样。假设您正在编写扫雷游戏。您的模型 class 表示扫雷板上的一个图块可能具有 hasMine: BoolxPos: IntyPos: Int 等属性。它还有一个 属性 存储用户单击磁贴 numberOfMinesNearby: Int? 时将显示的数字。请注意,它被声明为可选整数。为什么?因为如果那个方块有地雷,当用户点击它时不会显示任何数字!它只是爆炸!基本上,存储该图块周围地雷数量的想法是不适用的,因此它具有 nil.

的值

另一种使用可选值的情况是您懒得为 class 创建初始化程序,或者您想用其他方法进行初始化,例如 viewDidLoad.

class MyModel {
    var property: String?
    var anotherProperty: Int?
}

class MyViewController: UIViewController {
    var property: String?
    var anotherProperty: Int?
    override func viewDidLoad() {
        property = "hello"
        anotherProperty = 10
    }
}

如果您确定每次创建新的 MyModel 对象时都会分配 propertyanotherProperty,则可以使它们成为隐式展开的可选对象:

class MyModel {
    var property: String!
    var anotherProperty: Int!
}

class MyViewController: UIViewController {
    var property: String!
    var anotherProperty: Int!
    override func viewDidLoad() {
        property = "hello"
        anotherProperty = 10
    }
}

这会导致可选项在您使用时被隐式强制解包。

我刚刚解释了可选值的另外两个优点 - 使您的代码有意义并节省您编写初始化程序的时间。当你写更多的代码时,你一定会发现更多。

为了满足编译器的要求,我们要么分配如下值:

aString = "hello"

或者在我们事先不知道值或者是否会有值的情况下,我们告诉编译器该变量是可选类型。

var aString : String?

这满足了编译器的要求,并允许该值可以是 nil 或非 nil,而不会在代码中的任何一种情况下出错。

例如,假设您有一个 class 来代表用户的朋友和他们的 stockImageID,以及他们是否有个人资料图片(在您可能需要的多种属性中):

class friend {
    var stockImageID: Int!
    var profilePicture: UIImage?
}

您可以在地址簿中搜索他的朋友(联系人)的照片以及带照片的联系人:

myFriend.profilePicture = profilePictureFromAddressBook

不过很多朋友不会有照片。对于这些朋友,您将使用他们的图片 ID(每个朋友都有一个,注意 ! 它告诉编译器每个朋友都会有一个),它与您用来随机分配用户个人资料图片的图片库相关联。

能够使 profilePicture 可选在这里非常有用,因为在代码的其他区域,您不知道哪些朋友有 profilePicture 而哪些没有。作为一个可选的,你将能够安全而优雅地处理提前不知道这一点的事情,比如:

if let profilePicture = myFriend.profilePicture {
    print("display profile picture...")
}
else {
    let profilePicture = stockImageDictionary["myFriend.stockImageID"]
    print("display profile picture...")
}

希望这对一些人有所帮助。随着花在该语言上的时间越多,可选值的使用就越明显。恕我直言,他们真的很好。

  • 使用带有变量的 ?! 意味着两者都是 optional.
  • !这个符号表示隐式解包可选。
  • 而且如果我们使用?符号和一个变量,我们必须在使用它的时候解包。
  • 在我的例子中,没有 optional 的变量不能为 nil。例如:

var valueOne : Int = 4 // this cannot be nil

  • 并且使用 ? menas 其 typeoptional

var valueTwo :Int? = 8 //type of this variable is Optional Int and this can be nil. and also when we use this we have to unwrap it and should check whethe this is nil or not like below

valueOne + valueTwo!

if let newVal = valueTwo{
     valueOne + newVal //check the value is nil or not
}
  • 终于使用 !隐式解包可选

var valueThree : Int! = 12 // type of this variable is implicitly unwrapped optional Int we do not need to unwrap when we do any operation with it like below. this also can be nil

valueOne + valueThree