【问题标题】:What's the benefit of Apple having used struct with static properties (instead of enum) for UITextContentType?Apple 对 UITextContentType 使用具有静态属性(而不是枚举)的 struct 有什么好处?
【发布时间】:2020-05-18 21:59:15
【问题描述】:

在 Swift 中,Apple 的 UITextContentType 是一个具有许多 UITextContentType 类型的静态属性的结构体,例如:

  • static let URL: UITextContentType
  • static let addressCity: UITextContentType
  • static let addressCityAndState: UITextContentType

等等。

但 UIKit/UITextInputTraits.h 有:

typedef NSString * UITextContentType NS_TYPED_ENUM;

而且我注意到,在 Swift 中,编译器推断 UITextContentType,允许您简单地使用 .URL.addressCityAndState 而不是 UITextContentType.URLUITextContentType.addressCityAndState 用于任何采用 UITextContentType 类型的函数参数(因此像枚举一样对待它)。

那么他们为什么不直接使用enum 开头呢?使用这种模式有什么好处......?我们什么时候想在自己的代码中使用这种模式?

【问题讨论】:

    标签: swift struct enums uikit uitextfield


    【解决方案1】:

    我注意到 Apple 也使用 SKAction 来做到这一点。每个动作都是静态属性。 我希望他们在这种情况下使用了枚举。 ha

    Static PropertiesEnum Cases 之间有一些区别。
    但实际上,如何使用它们取决于您。


    静态属性的优点
    • 您不必在每次需要原始值时都使用 switch 语句
    • 原始值可以包含可变的非文字值。
    • 静态属性可以是任何你想要的类型static let a = 5, b = false
    • 您可以为枚举、结构、类、协议添加静态属性

    静态属性的缺点
    • 它们不能像非静态值那样具有“存储属性”
    • 它们不是 CaseIterable


    枚举的优点
    • 您可以将值存储在案例case hello(String, [Bool])
    • 您可以使用间接枚举拥有递归存储属性
    • 案例可以是 CaseIterable

    枚举的缺点
    • 您不能有多个 rawValue 类型 case foo = "5", bar = 5
    • 原始值类型不能包含值。 case foo = "\(5)"
    • 到处都是那些棘手的 switch case 语句
    • 您不能将枚举案例添加到非枚举对象

    【讨论】:

      猜你喜欢
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多