ios - 在函数内部使用关键字 guard 是否会自动使函数的参数在 swift 中成为可选参数?

标签 ios swift uiimagepickercontroller apple-documentation

我是编程新手,正在阅读 Start Developing iOS Apps (Swift) programming guide .我知道可选项有一个问号后缀,这意味着该值可以是 nil 或其他一些值。 Apple 的指南向我们介绍了如何使用 UIImagePickerController 及其委托(delegate)。 Apple 使用委托(delegate)方法 imagePickerControllerdidFinishPickingMediaWithInfo(_:),它有一个字典作为参数。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
    }

Apple's UIImagePickerControllerDelegate documentation没有将此参数列为可选参数,我们为本教程创建的 UIImagePickerController 实例也不是可选参数,但本教程声明如下:

"This code accesses the original, unedited image from the info dictionary. It safely unwraps the optional returned by the dictionary and casts it as a UIImage object. The expectation is that the unwrapping and casting operations will never fail. If they do, it represents either a bug in your app that needs to be fixed at design time."

这是否意味着通过使用 guard 关键字,它会自动将变量变为可选变量?

最佳答案

没有。可选值源于尝试从字典中检索值。虽然 info 参数是 [String: Any] 类型的非可选字典,但下标引用 info[UIImagePickerControllerOriginalImage] 返回一个可选值类型 Any?

来自 The Swift Programming Language (Swift 3.0.1) , "访问和修改字典":

Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// Prints "The name of the airport is Dublin Airport."

关于ios - 在函数内部使用关键字 guard 是否会自动使函数的参数在 swift 中成为可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41774974/

相关文章:

ios - UIScrollView 不滚动 Swift 3

ios - 用透明按钮覆盖堆栈 View

ios - 使用 ASNetworkImageNode 下载图像后从 AsyncDisplayKit 重新布局 ASTableView

swift - 将图像保存到 Cloud Firestore

swift - 如何快速检查对象数组中是否存在属性值

objective-c - iOS:UIImageView 问题

ios - iOS 10 中的调用阻止功能

uiimagepickercontroller - 如何在 swift 中使用 UIImagePickerController 捕获相机?

objective-c - 如何将图像 URL 保存到照片库并随后使用保存的图像

ios - UITableViewRow 显示没有颜色的按钮