why swift use a struct as dictionary key instead of a string here?

ε祈祈猫儿з 提交于 2019-12-20 03:08:14

问题


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.



来源:https://stackoverflow.com/questions/56147956/why-swift-use-a-struct-as-dictionary-key-instead-of-a-string-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!