why swift use a struct as dictionary key instead o

2020-04-17 04:31发布

问题:

Why UIImagePickerController.InfoKey type is struct not a string ,what is the benefit to use struct as a dictionary key instead of string?

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)

回答1:

It's simple, the benefit is the ability to check key values during compilation. This way, you won't be able to pass a String directly and if you do, you have to manually wrap it into a InfoKey structure, making your intention clear.

Most of the times you should be using one of the predefined constants.

An enum would be a better solution but probably that would break some existing code (and cannot be really enforced in Objective-C).

If Apple engineers were creating a new API today, they wouldn't probably even use a dictionary but they would use a custom object to pass the values to the delegate method.