苹果公司的文件如下:
您可以一起使用if和let来处理可能丢失的值。这些值表示为可选项。可选值要么包含值,要么包含nil,表示该值缺失。在值的类型后面写一个问号(?),将该值标记为可选值。
为什么要使用可选值?
苹果公司的文件如下:
您可以一起使用if和let来处理可能丢失的值。这些值表示为可选项。可选值要么包含值,要么包含nil,表示该值缺失。在值的类型后面写一个问号(?),将该值标记为可选值。
为什么要使用可选值?
当前回答
可选意味着Swift不能完全确定该值是否与类型对应:例如,Int?这意味着Swift不能完全确定该数字是否是Int类型。
要去除它,可以采用三种方法。
1)如果你绝对确定它的类型,你可以使用感叹号来强制打开它,就像这样:
// Here is an optional variable:
var age: Int?
// Here is how you would force unwrap it:
var unwrappedAge = age!
如果你强制打开一个可选对象并且它等于nil,你可能会遇到这个崩溃错误:
这并不一定是安全的,所以这里有一个方法,可以防止崩溃,如果你不确定类型和值:
方法二和方法三防止了这个问题。
2)隐式解包装可选
if let unwrappedAge = age {
// continue in here
}
注意,展开的类型现在是Int,而不是Int?
3)警卫声明
guard let unwrappedAge = age else {
// continue in here
}
在这里,您可以继续使用未包装变量。如果您确定变量的类型,请确保仅强制展开(使用!)。
祝你的项目好运!
其他回答
下面是Swift中等价的可选声明:
var middleName: String?
这个声明创建了一个名为midlename的String类型变量。String变量类型后面的问号(?)表示middleame变量可以包含String或nil值。看过这段代码的人都知道middleame可以是nil。这是自我记录!
如果你没有为一个可选的常量或变量指定一个初始值(如上所示),这个值会自动为你设置为nil。如果你愿意,你可以显式地将初始值设置为nil:
var middleName: String? = nil
有关可选选项的更多详细信息,请阅读下面的链接
http://www.iphonelife.com/blog/31369/swift-101-working-swifts-new-optional-values
从https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html:
可选链接是一个查询和调用属性、方法和当前可能为nil的可选对象的下标的过程。如果可选选项包含值,则属性、方法或下标调用成功;如果可选值为nil,则属性、方法或下标调用将返回nil。多个查询可以链接在一起,如果链中的任何链接为nil,整个链就会优雅地失败。
要更深入地了解,请阅读上面的链接。
嗯…
? (可选)表示您的变量可能包含nil值,而!(unwrapper)表示在运行时使用变量(试图从中获取值)时,变量必须具有内存(或值)。
主要的区别是,当可选对象为nil时,可选链接会优雅地失败,而当可选对象为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
以下是苹果开发者委员会提供的基本教程:可选链接
当我开始学习Swift时,很难意识到为什么是可选的。
让我们这样想。 让我们考虑一个类Person,它有两个属性名和公司。
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!!!
}
咱们把鲍勃换成汤姆吧
if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
print(companyString+" Inc") //Will executed and no crash!!!
}
和祝贺!我们是否妥善处理可选事宜?
实现要点是
如果一个变量可能为nil,我们将其标记为可选 如果我们想在代码的某个地方使用这个变量,编译器将 提醒你们一下,我们需要检查一下我们是否正确地处理了这个变量 如果它包含nil。
谢谢你!快乐的编码
在objective C中,没有值的变量等于“nil”(也可以使用与0和false相同的“nil”值),因此可以在条件语句中使用变量(有值的变量与“TRUE”相同,而那些没有值的变量等于“false”)。
Swift通过提供“可选值”来提供类型安全。即,它可以防止因分配不同类型的变量而形成错误。
所以在Swift中,只有条件语句可以提供布尔值。
var hw = "Hello World"
这里,虽然'hw'是一个字符串,但它不能像objective - C那样在if语句中使用。
//This is an error
if hw
{..}
为此,它需要被创建为,
var nhw : String? = "Hello World"
//This is correct
if nhw
{..}