简体   繁体   English

如何在Swift 2中使用可选绑定

[英]How to use optional binding in Swift 2

I'm new to learning Swift so I decided I might as well learn Swift 2 instead. 我是学习Swift的新手,所以我决定不再学习Swift 2。 Everything has made sense to me so far except for the following code snippet. 到目前为止,除了以下代码片段之外,一切对我都有意义。 Hopefully someone can shed some light on this for me. 希望有人可以为我阐明这一点。

//: Playground - noun: a place where people can play
import UIKit

//Works
let possibleNumber="2"
if let actualNumber = Int(possibleNumber) {
    print("\'\(possibleNumber)\' has an integer value of \(actualNumber)")
}
else {
    print("could not be converted to integer")
}

//Doesn't Work and I'm not sure why
let testTextField = UITextField()
testTextField.text = "2"
let numberString = testTextField.text  //I know this is redundant

if let num = Int(numberString) {
    print("The number is: \(num)")
}
else {
    print("Could not be converted to integer")
}

The top section of the code is straight from Apple's Swift 2 ebook and it makes sense to me how it uses optional binding to convert the string to an int. 代码的顶部部分直接来自Apple的Swift 2电子书,对我来说如何使用可选绑定将字符串转换为int是有意义的。 The second piece of code is basically the same except that the string comes from the text property of a UITextField. 第二段代码基本相同,只是字符串来自UITextField的text属性。 The bottom part of the code gives the following error: 代码的底部给出以下错误:

Playground execution failed: /var/folders/nl/5dr8btl543j51jkqypj4252mpcnq11/T/./lldb/843/playground21.swift:18:18: error: value of optional type 'String?' 游乐场执行失败:/var/folders/nl/5dr8btl543j51jkqypj4252mpcnq11/T/./lldb/843/playground21.swift:18:18:错误:可选类型'String?'的值 not unwrapped; 没有打开; did you mean to use '!' 你的意思是用'!' or '?'? 要么 '?'? if let num = Int(numberString) { if let num = Int(numberString){

I fixed the problem by using this line: 我通过使用这一行解决了这个问题:

if let num = Int(numberString!) {

I just want to know why the second example needs the ! 我只是想知道为什么第二个例子需要! and the first doesn't. 而第一个没有。 I'm sure the problem has to do with the fact that I'm getting the string from a textfield. 我确定问题与我从文本字段中获取字符串这一事实有关。 Thanks! 谢谢!

The difference is that in the first case possibleNumber is not an optional variable. 不同之处在于,在第一种情况下, possibleNumber不是可选变量。 It is definitely a string. 这绝对是一个字符串。 It cannot be nil. 它不能是零。

In the second case textField.text returns an optional string and so numberString is an optional variable. 在第二种情况下, textField.text返回一个可选字符串,因此numberString是一个可选变量。 It could be nil. 它可能是零。

Now... The conversion Int("") returns an optional int. 现在......转换Int("")返回一个可选的int。 if the string is "abc" then it cannot return a number so returns nil. 如果字符串是“abc”,那么它不能返回一个数字,所以返回nil。 This is what you are unwrapping with the if let... statement. 这就是你用if let...语句展开的内容。

However, in the second case your string is also optional and the Int() will not accept an optional. 但是,在第二种情况下,您的字符串也是可选的,Int()将不接受可选字符串。 So you are force unwrapping it. 所以你强行打开它。 This is dangerous as it could crash the app if the string is nil. 这很危险,因为如果字符串为零,它可能会使应用程序崩溃。

What you could do instead is this... 你可以做的是......

if let numberString = textFeidl.text,
    number = Int(numberString) {
    // use the number
}

This will unwrap the text first and if it's available then use it to. 这将首先解开文本,如果它可用,则使用它。 Get the number. 得到号码。 If that is not nil then you enter the block. 如果那不是零则输入块。

In Swift 2 you could use the guard let function here also. 在Swift 2中你也可以在这里使用guard let功能。

Just seen that you are using Swift 2. 刚刚看到你正在使用Swift 2。

You can do it this way also... 你也可以这样做......

func getNumber() -> Int {
    guard let numberString = textField.text,
          number = Int(numberString)
          else {
          return 0
    }

    return number
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM