为什么Apple使用这个“if let”代码?

时间:2015-09-24 09:08:10

标签: ios iphone swift

Apple在其中一个示例项目中有这段代码:

    let existingImage = cache.objectForKey(documentIdentifier) as? UIImage

    if let existingImage = existingImage where cleanThumbnailDocumentIDs.contains(documentIdentifier) {
        return existingImage
    }

为什么苹果使用此if let?简单地使用

更合乎逻辑
    if cleanThumbnailDocumentIDs.contains(documentIdentifier) {
        return existingImage!
    }

??? !!

6 个答案:

答案 0 :(得分:2)

如果您使用

  let existingImage = cache.objectForKey(documentIdentifier) as? UIImage

if let existingImage = existingImage where cleanThumbnailDocumentIDs.contains(documentIdentifier) {
    return existingImage
}
  • 这将确保如果existingImage == nil,则不会 执行return existingImage
  • 此外,if let还会从existingImageUIImage?展开UIImage src

答案 1 :(得分:1)

正如Abhinav所述,Apple推出了一种名为Swift的可选类型。

可选是什么意思?

Short and Sweet,"可选类型是类型,可以包含特定数据类型的值或nil"。

您可以在此处详细了解选项及其优势:swift-optionals-made-simple

现在,只要您想要使用可选类型中存在的值,首先需要检查它包含的内容,即它是否包含正确的值,或者它包含nil。此过程称为可选展开

现在有两种类型的展开,

  1. 强制展开:如果您确定某个选项会一直有值,则可以使用" &#打开可选类型中的值。 34;标记。这是力量展开。
  2. 还有一种方法是使用如果让表达式,这是安全的解包,在这里您将检查您的程序,如果可选的有值,您将执行某些操作用它;如果它没有包含价值,你就可以做其他事情。一个简单的例子就是这个(你可以在游戏场测试这个:

    func printUnwrappedOptional (opt:String?) {
    
    
    if let optionalValue = opt { //here we try to assign opt value to optionalValue constant, if assignment is successful control enters if block
    
    
        println(optionalValue) // This will be executed only if optionalValue had some value
    }
    else {
        println("nil")
    }}
    var str1:String? = "Hello World" //Declaring an optional type of string and assigning it with a value
    
    var str2:String? //Declaring an optional type of string and not assigning any value, it defaults to nil
    
    printUnwrappedOptional(str1) // prints "Hello World"
    
    printUnwrappedOptional(str2) // prints "nil"
    
  3. 希望这能解决您的问题,请仔细阅读上面给出的链接,以便您更清楚。希望这可以帮助。 :)

    编辑:在Swift 2.0中,Apple推出了" 后卫"声明,一旦您对选项有好处,请通过此链接guard statement in swift 2。这是处理期权的另一种方式。

答案 2 :(得分:0)

使用if let,确保对象(existingImage)不是nil,并自动解包,因此您确定条件为true,并且对象不是没有,你可以使用它而无需打开它!

答案 3 :(得分:0)

通过Swift,Apple推出了一种新概念/类型 - 可选类型。我认为你最好通过Apple Documentation

  

Swift还引入了可选类型,它们可以处理缺少的类型   值。 Optionals说“有一个值,它等于x”或者   “根本没有价值”。可选项类似于使用nil   Objective-C中的指针,但它们适用于任何类型,而不仅仅是类。   可选项比nil指针更安全,更具表现力   Objective-C是Swift最强大的许多人的核心   特征

答案 4 :(得分:0)

existingImage是可选的(as? UIImage),因此需要在使用之前解包,否则会出现编译错误。您正在做的是通过!强制解包。你的程序会崩溃,如果是existingImage == nil,那么只有在你完全确定的情况下才可行,existingImage不能为零

答案 5 :(得分:0)

如果让可选类型更有帮助,那么可以通过更改获取nil值来消除崩溃和不需要的代码执行。

在Swift 2.0中,

  

护卫

如果不满足特定条件,

将帮助我们明确我们的意图,不执行其余代码

相关问题