为什么 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/