【问题标题】:Is it possible to specify the object type allowed in a Dictionary?是否可以指定字典中允许的对象类型?
【发布时间】:2017-01-04 16:14:45
【问题描述】:

在 Swift 3.x 中是否可以指定字典中允许的对象类型?

如果在声明时我们可以传递一组允许的对象类型,那就太好了。

【问题讨论】:

  • 您可以通过协议或基类来做到这一点。
  • 我想避免使用基类,但是通过协议听起来很有趣。你有例子吗?
  • 您能给我们一个具体的例子来说明您正在寻找什么吗?如果您想讨论一组不一定具有共同功能的有限类型,enum 可能就是您所追求的。

标签: swift dictionary swift3 object-type


【解决方案1】:

您可以通过自定义协议实现此目的,该协议仅由您希望在字典中允许的类型实现:

protocol AllowedDictionaryValue: {}

extension String: AllowedDictionaryValue {}
extension Int: AllowedDictionaryValue {}
extension MyClass: AllowedDictionaryValue {}
extension MyEnum: AllowedDictionaryValue {}

let dictionary: [String:AllowedDictionaryValue] = ...

上述字典将仅包含 String's、Int's、MyClass 实例和 MyEnum 值。

这样你就可以在字典中只包含你想要的值,同时保持字典的异构性。

【讨论】:

    【解决方案2】:

    您可以使用具有关联值的枚举来完成此行为,这在其他语言中称为标记联合。它基本上是一种可以将类型限制为任意类型集而不是 Any 或 AnyObject 的方法。枚举部分是告诉您拥有什么样的数据的标签,关联的值是该类型的实际数据。并不是说使用 Any 或 AnyObject 的优势在于 switch 语句是详尽无遗的,编译器可以强制您在编译时处理所有情况,而如果您将 Any 与 if let 语句链一起使用,则情况并非如此。

        import PlaygroundSupport
        import UIKit
    
    
        enum Number {
            case integer(Int), double(Double), currency(NSDecimalNumber)
        }
        var dictionary: [String : Number] = [ "a" : .integer(1), "b" : .double(2), "c" : .currency(NSDecimalNumber(value: 3))]
    
        for (key, value) in dictionary {
            switch value {
            case .integer(let number):
                print ("\(key) has a type of \(type(of: number)) with a value of \(number)")
            case .double(let number):
                print ("\(key) has a type of \(type(of: number)) with a value of \(number)")
            case .currency(let number):
                print ("\(key) has a type of \(type(of: number)) with a value of \(number)")
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多