Swift中的可选值是什么?

时间:2014-06-02 21:32:30

标签: swift optional

来自Apple's documentation

  

您可以一起使用iflet来处理可能缺失的值。这些值表示为选项。可选值包含值或包含nil以指示缺少值。在值的类型后面写一个问号(?),将值标记为可选。

为什么要使用可选值?

12 个答案:

答案 0 :(得分:15)

我们以NSError为例,如果没有返回错误,您可以选择返回Nil。如果没有错误,那么为它赋值是没有意义的。

var error: NSError? = nil

这也允许您拥有默认值。因此,如果函数未传递任何内容

,则可以将方法设置为默认值
func doesntEnterNumber(x: Int? = 5) -> Bool {
    if (x == 5){
        return true
    } else {
        return false
    }
}

答案 1 :(得分:12)

你不能在Swift中有一个指向nil的变量 - 没有指针,也没有空指针。但是在API中,您通常希望能够指出特定类型的值或缺乏价值 - 例如我的窗口有一个代表,如果有,那是谁?可选项是Swift的类型安全,内存安全的方法。

答案 2 :(得分:11)

我做了一个简短的回答,总结了上面的大部分内容,以清除我作为初学者的不确定性:

与Objective-C相反,Swift中没有变量可以包含 nil ,因此添加了Optional变量类型(变量后缀为“?”):

    var aString = nil //error

最大的区别在于可选变量不直接存储值(正常的Obj-C变量)它们包含两个状态:“具有值 “或”没有“:

    var aString: String? = "Hello, World!"
    aString = nil //correct, now it contains the state "has nil"

那就是,您可以在不同情况下检查这些变量:

if let myString = aString? {
     println(myString)
}
else { 
     println("It's nil") // this will print in our case
}

使用“!”后缀,您还可以访问其中包含的值,仅当存在时。 (即它不是):

let aString: String? = "Hello, World!"
// var anotherString: String = aString //error
var anotherString: String = aString!

println(anotherString) //it will print "Hello, World!"

这就是你需要使用“?”的原因。和“!”并且默认情况下不使用所有这些。 (这是我最大的困惑)

我也同意上面的答案:可选类型不能用作布尔值

答案 3 :(得分:7)

在目标C中,没有值的变量等于'nil'(也可以使用与0和false相同的'nil'值),因此可以在条件语句中使用变量(具有值的变量是相同的)为'TRUE'而没有值的那些等于'FALSE')。

Swift通过提供“可选值”来提供类型安全性。即它可以防止因分配不同类型的变量而形成的错误。

所以在Swift中,只能在条件语句中提供布尔值。

var hw = "Hello World"

这里,虽然'hw'是一个字符串,但它不能像在目标C中那样用在if语句中。

//This is an error

if hw

 {..}

为此,需要将其创建为,

var nhw : String? = "Hello World"

//This is correct

if nhw

 {..}

答案 4 :(得分:5)

可选值允许您显示缺少值。有点像SQL中的NULL或Objective-C中的NSNull。我想这将是一个改进,因为即使是“原始”类型也可以使用它。

// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
    case None
    case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)”

摘自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itun.es/gb/jEUH0.l

答案 5 :(得分:3)

可选意味着Swift不完全确定该值是否与类型相对应:例如,Int?意味着Swift并不完全确定该数字是否为Int。

  

要删除它,您可以使用三种方法。

1)如果您完全确定类型,可以使用感叹号强行打开它,如下所示:

j

如果您强行打开一个可选项并且它等于nil,则可能会遇到此崩溃错误:

enter image description here

这不一定是安全的,所以这里有一种方法可以防止崩溃,以防您不确定类型和值:

  

方法2和3防止这个问题。

2)隐式解包可选

// Here is an optional variable:

var age: Int?

// Here is how you would force unwrap it:

var unwrappedAge = age!
  

请注意,展开的类型现在是 Int ,而不是 Int?

3)守卫声明

 if let unwrappedAge = age {

 // continue in here

 }

从这里开始,您可以继续使用未包装的变量。如果您确定变量的类型,请确保仅强制打开(使用!)。

  

祝你的项目好运!

答案 6 :(得分:1)

当我开始学习Swift时,很难意识到为什么选择

让我们以这种方式思考。 考虑一个具有两个属性Personname的小组company

class Person: NSObject {

    var name : String //Person must have a value so its no marked as optional
    var companyName : String? ///Company is optional as a person can be unemployed that is nil value is possible

    init(name:String,company:String?) {

        self.name = name
        self.companyName = company

    }
}

现在让我们创建一些Person

的对象
var tom:Person = Person.init(name: "Tom", company: "Apple")//posible
var bob:Person = Person.init(name: "Bob", company:nil) // also Possible because company is marked as optional so we can give Nil

但我们无法将Nil传递给name

var personWithNoName:Person = Person.init(name: nil, company: nil)

现在让我们谈谈我们使用optional?的原因。 让我们考虑一下我们想要在Inc之类的公司名称apple之后添加apple Inc的情况。我们需要在公司名称和打印之后附加Inc

print(tom.companyName+" Inc") ///Error saying optional is not unwrapped.
print(tom.companyName!+" Inc") ///Error Gone..we have forcefully unwrap it which is wrong approach..Will look in Next line
print(bob.companyName!+" Inc") ///Crash!!!because bob has no company and nil can be unwrapped.

现在让我们研究一下为什么选择可行。

if let companyString:String = bob.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.

    print(companyString+" Inc") //Will never executed and no crash!!!
}

让我们用bob

替换tom
if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.

    print(companyString+" Inc") //Will never executed and no crash!!!
}

祝贺!我们已妥善处理optional?

所以实现点是

  1. 如果变量可能是nil
  2. ,我们会将变量标记为可选
  3. 如果我们想在代码编译器的某个地方使用这个变量 提醒您,我们需要检查我们是否正确处理该变量 如果它包含nil
  4. 谢谢......快乐编码

答案 7 :(得分:0)

来自https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

  

可选链接是一个查询和调用当前可能为nil的可选项的属性,方法和下标的过程。如果optional包含值,则属性,方法或下标调用成功;如果optional是nil,则属性,方法或下标调用返回nil。多个查询可以链接在一起,如果链中的任何链接为零,整个链都会正常失败。

要深入了解,请阅读上面的链接。

答案 8 :(得分:0)

让我们尝试使用以下代码游乐场。我希望能够清楚知道什么是可选项以及使用它的原因。

var sampleString: String? ///Optional, Possible to be nil

sampleString = nil ////perfactly valid as its optional

sampleString = "some value"  //Will hold the value

if let value = sampleString{ /// the sampleString is placed into value with auto force upwraped.

    print(value+value)  ////Sample String merged into Two
}

sampleString = nil // value is nil and the

if let value = sampleString{

    print(value + value)  ///Will Not execute and safe for nil checking
}

//   print(sampleString! + sampleString!)  //this line Will crash as + operator can not add nil

答案 9 :(得分:0)

嗯...

  

<强>? (可选)表示您的变量在时可能包含零值! (unwrapper)表示你的变量在运行时使用(尝试从中获取值)时必须有一个内存(或值)。

主要区别在于,当optional是nil时,可选链接正常失败,而当optional是nil时,强制解包会触发运行时错误。

为了反映可以在nil值上调用可选链接的事实,可选链接调用的结果始终是可选值,即使您要查询的属性,方法或下标返回非可选值。您可以使用此可选返回值来检查可选链接调用是否成功(返回的可选项包含值),或者由于链中的nil值(返回的可选值为nil)而未成功。

具体来说,可选链接调用的结果与预期返回值的类型相同,但包含在可选中。通过可选链接访问时,通常返回Int的属性将返回 Int?

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

这是Apple开发者委员会的详细基础教程:Optional Chaining

答案 10 :(得分:0)

Swift中的可选参数是可以保存值或不保存值的类型。通过将附加到任何类型来编写可选内容:

var name: String?

您可以参考此链接以深入了解知识:https://medium.com/@agoiabeladeyemi/optionals-in-swift-2b141f12f870

答案 11 :(得分:-1)

这是Swift中的等效可选声明:

var middleName: String?

此声明创建一个名为middleName的String类型的变量。 String变量类型​​后面的问号(?)表示middleName变量可以包含一个可以是String或nil的值。任何查看此代码的人都会立即知道middleName可以为零。它是自我记录的!

如果没有为可选常量或变量指定初始值(如上所示),则该值会自动设置为nil。如果您愿意,可以将初始值显式设置为nil:

var middleName: String? = nil

有关可选阅读以下链接

的更多详细信息

http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values