Swift中的通用字典值类型

时间:2022-03-02 16:12:59

I'm trying to create a dictionary variable whose values are one of two types. An example of my attempt should make this clearer:

我正在尝试创建一个字典变量,其值是两种类型之一。我的尝试的一个例子应该更清楚:

var objects: <T where T: Float, T: Bool>[String: T]

This throws a compiler error that only syntactic function types can be generic. I wonder if it is possible, I just don't know the correct syntax?

这会引发编译器错误,只有语法函数类型可以是通用的。我想知道是否有可能,我只是不知道正确的语法?

1 个解决方案

#1


15  

The tool you want for this is an enum with associated data.

您想要的工具是带有相关数据的枚举。

enum Stuff {
  case FloatyThing(Float)
  case BoolyThing(Bool)
}

let objects = ["yes!"   : Stuff.BoolyThing(true),
               "number" : Stuff.FloatyThing(1.0)]

This captures "an object that is either a float or a bool" and provides better documentation and type safety.

这捕获了“浮动或布尔的对象”,并提供更好的文档和类型安全性。

To unload the data, you use a switch statement:

要卸载数据,请使用switch语句:

if let something = objects["yes!"] {
  switch something {
    case .FloatyThing(let f): println("I'm a float!", f)
    case .BoolyThing(let b): println("Am I true?", b)
  }
}

The use of the switch statement makes sure you cover all the possible types and prevents you from accidentally unloading the data as the wrong type. Pretty nice that the compiler can help you so much.

使用switch语句可确保覆盖所有可能的类型,并防止您意外地将数据卸载为错误的类型。非常好,编译器可以帮助你这么多。

For more, see "Enumerations and Structures" in the Swift Programming Language.

有关更多信息,请参阅Swift编程语言中的“枚举和结构”。

I also recommend Error Handling in Swift by Alexandros Salazar for a very nice example of how this can be used to deal with common problems.

我还推荐Alexandros Salazar在Swift中进行错误处理,这是一个非常好的例子,说明如何使用它来处理常见问题。

#1


15  

The tool you want for this is an enum with associated data.

您想要的工具是带有相关数据的枚举。

enum Stuff {
  case FloatyThing(Float)
  case BoolyThing(Bool)
}

let objects = ["yes!"   : Stuff.BoolyThing(true),
               "number" : Stuff.FloatyThing(1.0)]

This captures "an object that is either a float or a bool" and provides better documentation and type safety.

这捕获了“浮动或布尔的对象”,并提供更好的文档和类型安全性。

To unload the data, you use a switch statement:

要卸载数据,请使用switch语句:

if let something = objects["yes!"] {
  switch something {
    case .FloatyThing(let f): println("I'm a float!", f)
    case .BoolyThing(let b): println("Am I true?", b)
  }
}

The use of the switch statement makes sure you cover all the possible types and prevents you from accidentally unloading the data as the wrong type. Pretty nice that the compiler can help you so much.

使用switch语句可确保覆盖所有可能的类型,并防止您意外地将数据卸载为错误的类型。非常好,编译器可以帮助你这么多。

For more, see "Enumerations and Structures" in the Swift Programming Language.

有关更多信息,请参阅Swift编程语言中的“枚举和结构”。

I also recommend Error Handling in Swift by Alexandros Salazar for a very nice example of how this can be used to deal with common problems.

我还推荐Alexandros Salazar在Swift中进行错误处理,这是一个非常好的例子,说明如何使用它来处理常见问题。