ios - 为什么 swift 在此处使用结构作为字典键而不是字符串?

标签 ios swift dictionary uiimagepickercontroller

为什么 UIImagePickerController.InfoKey 类型是结构而不是字符串,使用结构作为字典键而不是字符串有什么好处?

public struct InfoKey : Hashable, Equatable, RawRepresentable {

    public init(rawValue: String)
}
}
extension UIImagePickerController.InfoKey {


public static let mediaType: UIImagePickerController.InfoKey

public static let originalImage: UIImagePickerController.InfoKey // a UIImage

public static let editedImage: UIImagePickerController.InfoKey // a UIImage

public static let cropRect: UIImagePickerController.InfoKey // an NSValue (CGRect)

最佳答案

很简单,好处就是可以在编译时检查键值。这样,您将无法直接传递 String,如果这样做,您必须手动将其包装到 InfoKey 结构中,以明确您的意图。

大多数时候您应该使用预定义常量之一。

enum 将是更好的解决方案,但可能会破坏一些现有代码(并且不能在 Objective-C 中真正强制执行)。

如果 Apple 工程师今天要创建一个新的 API,他们可能甚至不会使用字典,但他们会使用自定义对象将值传递给委托(delegate)方法。

关于ios - 为什么 swift 在此处使用结构作为字典键而不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56147956/

相关文章:

ios - 什么时候可以使用@IBOutlets?

ios - 带有按钮的 ScrollView 可以在点击时出现和消失

swift - 在 UITableViewCell 中按下完成按钮时无法关闭 KeyBoard

loops - 在 Ansible 中使用 with_dict 循环遍历注册变量

objective-c - 终止iPhone应用程序时调用什么方法?

objective-c - 实现一个将 block 用作回调的方法

ios7 - 将 Dictionary<String, Any> 附加到 Array 会抛出异常

ios - 使用另一个 UIImageView 的 UIImageViews 坐标范围

Python在格式化表达式中对字典进行排序

python - 将列表列表解析为字典到 pandas DataFrame 时忽略错误