苹果公司的文件如下:
您可以一起使用if和let来处理可能丢失的值。这些值表示为可选项。可选值要么包含值,要么包含nil,表示该值缺失。在值的类型后面写一个问号(?),将该值标记为可选值。
为什么要使用可选值?
苹果公司的文件如下:
您可以一起使用if和let来处理可能丢失的值。这些值表示为可选项。可选值要么包含值,要么包含nil,表示该值缺失。在值的类型后面写一个问号(?),将该值标记为可选值。
为什么要使用可选值?
当前回答
让我们实验下面的代码游乐场。我希望能明确什么是可选的和使用它的原因。
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
其他回答
There are lots of errors which are caused by people trying to use a value which is not set, sometime this can cause a crash, in objective c trying to call the methods of a nil object reference would just be ignored, so some piece of your code not executing and the compiler or written code has no way of telling your why. An optional argument let you have variables that can never be nil, and if you try to do build it the compiler can tell you before your code has even had a chance to run, or you can decide that its appropriate for the object to be undefined, and then the compiler can tell you when you try to write something that doesn't take this into account.
在调用nil对象的情况下,你可以直接
object?.doSomthing()
你已经明确地告诉编译器和任何阅读你代码的人,它的可能对象是nil,什么都不会发生。有时,只有在值存在时才希望出现几行代码,因此可以这样做
if let obj = object {
obj.doSomthing()
doSomethingto(obj)
}
这两个语句只会在object是什么东西时执行,简单地说,如果它不是什么东西,你可能想要停止整个代码块的其余部分
guard let obj = object {
return
}
obj.doSomthing()
doSomethingto(obj)
如果后面的所有内容都只适用于object,那么阅读起来会更简单,另一种可能是你想使用默认值
let obj = object ?? <default-object>
obj.doSomthing()
doSomethingto(obj)
现在obj将被赋值给某个对象,即使它是该类型的默认值
选项是有用的情况下一个值可能不会获得一个值,直到一些事件发生或您可以使用一个选项设置为零,以说它不再相关的或者需要设置和使用的一切它没有做任何与它,直到它是集,我喜欢用可选的方法之一是告诉我必须做点什么或者已经完成
func eventFired() {
guard timer == nil else { return }
timer = scheduleTimerToCall(method, in: 60)
}
func method() {
doSomthing()
timer = nil
}
这个sudo代码可以多次调用eventFired,但只有在第一次调用时才会调度一个计时器,一旦调度执行,它会运行一些方法并将计时器设置为nil,这样就可以调度另一个计时器。
一旦你明白了变量处于未定义状态你就可以用它来做任何事情。
可选值允许您显示没有值。有点像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)”
摘自:苹果公司《快速编程语言》。“iBooks。https://itun.es/gb/jEUH0.l
当我开始学习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。
谢谢你!快乐的编码
这很简单。可选(在Swift中)意味着变量/常数可以为空。你可以看到Kotlin语言实现了同样的事情,但从未将其称为“可选”。例如:
var lol: Laugh? = nil
等价于Kotlin:
var lol: Laugh? = null
在Java中是这样的:
@Nullable Laugh lol = null;
在第一个例子中,如果您没有在对象类型前面使用?符号,那么就会出现错误。因为问号意味着变量/常数可以为空,因此被称为可选的。
从https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html:
可选链接是一个查询和调用属性、方法和当前可能为nil的可选对象的下标的过程。如果可选选项包含值,则属性、方法或下标调用成功;如果可选值为nil,则属性、方法或下标调用将返回nil。多个查询可以链接在一起,如果链中的任何链接为nil,整个链就会优雅地失败。
要更深入地了解,请阅读上面的链接。