Swift中的通用字典值类型 [英] Generic dictionary value type in Swift

查看:266
本文介绍了Swift中的通用字典值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

你想要的工具是枚举与相关数据。

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)]

这将捕获一个float或bool的对象,并提供更好的文档和类型安全性。

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

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

To unload the data, you use a switch statement:

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)
  }
}

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

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.

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

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

我还建议由Alexandros Salazar 在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.

这篇关于Swift中的通用字典值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆