This question already has answers here:
Why would I use if and let together, instead of just checking if the original variable is nil? (Swift)
(2个答案)
四年前关闭。
苹果在他们的一个示例项目中有这段代码:
    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!
    }

???!!

最佳答案

如果你使用

  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

08-05 01:59