如何在switch语句之外访问Swift枚举关联值 [英] How to access a Swift enum associated value outside of a switch statement

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

问题描述

考虑:

enum Line {
    case    Horizontal(CGFloat)
    case    Vertical(CGFloat)
}

let leftEdge             =  Line.Horizontal(0.0)
let leftMaskRightEdge    =  Line.Horizontal(0.05)

如何在不使用switch语句的情况下直接访问 lefEdge 的关联值?

How can I access, say, lefEdge's associated value, directly, without using a switch statement?

let noIdeaHowTo          = leftEdge.associatedValue + 0.5

这甚至无法编译!

我看了这些 SO 问题,但没有答案似乎可以解决这个问题

I had a look at these SO questions but none of the answers seem to address this issue.

上面的 noIdeaHowTo 非编译行实际上应该是单行代码,但是因为关联值可以是任何类型,我什至看不到用户代码如何在le枚举本身中编写通用 get或associatedValue方法。

The noIdeaHowTo non compiling line above should really be that one-liner, but because the associated value can be any type, I fail to even see how user code could write even a "generic" get or associatedValue method in le enum itself.

我最终得出了这个结论,但这很严重,每次添加/修改案子时都需要我重新访问代码...

I ended up with this, but it is gross, and needs me to revisit the code each time I add/modify a case ...

enum Line {
    case    Horizontal(CGFloat)
    case    Vertical(CGFloat)

    var associatedValue: CGFloat {
        get {
            switch self {
                case    .Horizontal(let value): return value
                case    .Vertical(let value): return value
            }
        }
    }
}

任何指针都可以吗?

推荐答案

正如其他人所指出的那样,现在在Swift 2中是可行的。

As others have pointed out, this is now kind of possible in Swift 2:

import CoreGraphics

enum Line {
    case    Horizontal(CGFloat)
    case    Vertical(CGFloat)
}

let min = Line.Horizontal(0.0)
let mid = Line.Horizontal(0.5)
let max = Line.Horizontal(1.0)

func doToLine(line: Line) -> CGFloat? {
    if case .Horizontal(let value) = line {
        return value
    }
    return .None
}

doToLine(min) // prints 0
doToLine(mid) // prints 0.5
doToLine(max) // prints 1

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

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