swift - 是否可以使用 Swift 将元组放入枚举中?

标签 swift enums tuples

如果我有以下枚举:

enum FruitTuple
{
    static let Apple = (shape:"round",colour:"red")
    static let Orange = (shape:"round",colour:"orange")
    static let Banana = (shape:"long",colour:"yellow")
}

然后我有以下功能:

static func PrintFruit(fruit:FruitTuple)
{
    let shape:String = fruit.shape
    let colour:String = fruit.colour

    print("Fruit is \(shape) and \(colour)")
}

fruit.shapefruit.colour 上我得到错误:

“FruitTuple”类型的值没有成员“shape”

很公平,所以我改变了枚举类型:

enum FruitTuple:(shape:String, colour:String)
{
    static let Apple = (shape:"round",colour:"red")
    static let Orange = (shape:"round",colour:"orange")
    static let Banana = (shape:"long",colour:"yellow")
}

但是在枚举声明中我得到了错误:

从非命名类型继承 '(shape: String, colour: String)'

因此,问题是:是否有可能在枚举中包含一个元组并能够以这种方式引用它的组成部分?我只是错过了一些基本的东西吗?

最佳答案

正如@MartinR 所指出的。此外,根据 Apple 文档,“枚举案例可以指定任何类型的关联值与每个不同的案例值一起存储”。如果您想继续使用 enum,您可能需要执行以下操作:

static func PrintFruit(fruit:FruitTuple.Apple)
{
    let shape:String = fruit.shape
    let colour:String = fruit.colour

    print("Fruit is \(shape) and \(colour)")
}

我不确定你想要什么,但我想使用 typealias 可以帮助实现你的目标。

typealias FruitTuple = (shape: String, colour: String)

enum Fruit
{
    static let apple = FruitTuple("round" , "red")
    static let orange = FruitTuple("round", "orange")
    static let banana = FruitTuple("long", "yellow")
}

func printFruit(fruitTuple: FruitTuple)
{
    let shape:String = fruitTuple.shape
    let colour:String = fruitTuple.colour
}

关于swift - 是否可以使用 Swift 将元组放入枚举中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44972847/

相关文章:

ios - 触摸开始不被召唤

Kotlin 中的枚举和 With

c++ - 将python字典翻译成C++

mySQL 使用枚举而不是两个 boolean 字段有优势吗?

Swift 元组 - 不同于结构和彼此?

c++ - TMP : how to write template code which converts any struct into a tuple?

objective-c - 快速更改本地化时如何重新加载 Storyboard

ios - 在 UCollectionView 底部添加 Activity/Loading Indicator

ios - 在 tableView Swift 中选择 textField 时打开 New ViewController

使用 "..."选择枚举元素