【问题标题】:why swift use a struct as dictionary key instead of a string here?为什么 swift 在这里使用结构作为字典键而不是字符串?
【发布时间】:2019-05-15 11:10:29
【问题描述】:

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

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)

【问题讨论】:

    标签: ios swift dictionary uiimagepickercontroller


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 一些附加信息:类型在 Objective-C 标头中定义为 typedef NSString * UIImagePickerControllerInfoKey NS_TYPED_ENUM;NS_TYPED_ENUM 是它在 Swift 中的结构:developer.apple.com/documentation/swift/…
    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多