在 Swift 中访问枚举关联值 [英] Accessing an Enumeration association value in Swift

查看:28
本文介绍了在 Swift 中访问枚举关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我编写了一个非常无用的枚举,它定义了一个可能的带有 Int 或 Float 的 Number.

In this code I've written a really useless enum that defines a possible Number with Int or Float.

我无法理解如何访问我在关联中设置的值.如果我尝试打印它,我只会得到 (Enum Value)

I can't understand how can I access the value that I set with the association. If I try to print it I get just (Enum Value)

enum Number {
    case int (Int)
    case float (Float)
}

let integer = Number.int(10)
let float = Number.float(10.5)
println("integer is \(integer)")
println("float is \(float)")

推荐答案

该值与枚举的实例相关联.因此,要在没有开关的情况下访问它,您需要创建一个 getter 并使其显式可用.类似于以下内容:

The value is associated to an instance of the enumeration. Therefore, to access it without a switch, you need to make a getter and make it available explicitly. Something like below:

enum Number {
    case int(Int)
    case float(Float)

    func get() -> NSNumber {
        switch self {
        case .int(let num):
            return num
        case .float(let num):
            return num
        }
    }
}

var vInteger = Number.int(10)
var vFloat = Number.float(10.5)

println(vInteger.get())
println(vFloat.get())

也许将来会自动创建类似的东西,或者可以为语言添加更短的便利.

Maybe in the future something like that may be automatically created or a shorter convenience could be added to the language.

这篇关于在 Swift 中访问枚举关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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