我在想,如果它是我们在 Obj-c 中已经拥有的东西,根据 Optional Variables 的苹果的这个“强大的解决方案”实际上是如何强大的?

var mystring: String? = nil

if mystring {
  //string is not nil
}

第二个场景无法编译
var mystring: String = nil

if mystring {
  //string is not nil
}

之前我们可以在 Obj-C 中做到这一点,而无需任何额外的设置。
NSString * somestring = @"Test";

if(something != [NSNull null]){
  //Do something.
}

或者
NSString * anotherstring = nil;

if(anotherstring == [NSNull null]){
  //display error.
}

所以我真的很困惑,如果它已经存在于以前的语言中,那么它是如何强大的。

Some info about Optional Variables

最佳答案

在 Objective-C 中,指向对象的指针可能是 nil ,是的。但是没有强制执行 nil 是否有意义。

NSString *shouldNeverBeNil = @"a string!";
shouldNeverBeNil = nil;
NSLog("Hello, %@", shouldNeverBeNil); // "Hello, "

在 ObjC 中,这编译得很好,尽管我们永远不应该什么都不说。那是一个错误。

但是如果我们在 Swift 中做同样的事情,它甚至不会编译,我们根本不会遇到运行时错误。
var shouldNeverBeNil: String = "a string!"
shouldNeverBeNil = nil; // Compilation error.
NSLog("Hello, %@", shouldNeverBeNil); // never happens

Optionals 允许你祝福变量成为 nil 。编译错误总是比运行时错误更可取,因为您的应用程序的最终用户不可能遇到编译错误。

如果你想让这个值成为 nil Swift 会让你明确地祝福它,作为一个 Optional。现在,如果它是 nil ,则您明确允许它,并且 Swift 会提醒您处理代码中的 nil 情况和 value 情况。
var okToBeNil: String? = "a string!"
okToBeNil = nil;
if okToBeNil != nil {
  NSLog("Hello, %@", okToBeNil!); // never happens
} else {
  NSLog("What is your name?")
}

关于swift - 可选变量如何成为 "powerful solution"?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26024462/

10-12 14:39
查看更多