[swift-evolution] Consolidate Code for Each Case in Enum

David Sweeris davesweeris at mac.com
Sun Jan 8 12:05:23 CST 2017


> On Jan 8, 2017, at 06:53, Karim Nassar via swift-evolution <swift-evolution at swift.org> wrote:
> 
> One area of enums that I’d love to see some sugar wrapped around (and perhaps this has already been discussed previously?) is extracting associated values.
> 
> There are many times where, given an enum like:
> 
> enum Feedback {
> 	case ok
> 	case info(String)
> 	case warning(String, Location)
> 	case error(String, Location)
> }
> 
> I’d love it if we could tag the associated values with some semantic accessor, perhaps borrowed from tuples:
> 
> enum Feedback {
> 	case ok
> 	case info(msg: String)
> 	case warning(msg: String, loc: Location)
> 	case error(msg: String, loc: Location)
> }
> 
> then:
> 
> let foo = self.getSomeFeedback() // -> Feedback
> if let msg = foo.msg { // since not all cases can hold a ‘msg’ .msg is an Optional
> 	print(foo)
> }

Can't remember if it's come up before, but +1. I can't count how many times I've written something like:
enum Foo : CustomStringConvertible {
    case c1(T1)
    case c2(T2)
    ...
    case cN(TN)

    var description: String {
        switch self {
            case .c1(let val): return "\(val)"
            case .c2(let val): return "\(val)"
            ...
            case .cN(let val): return "\(val)"
        }
    }
}

Being able to simplify that to:
var description: String {
    let nilDesc = "some appropriate description"
    return "\(self.0 ?? nilDesc)"
}

Would be great.

- Dave Sweeris 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170108/bac58796/attachment.html>


More information about the swift-evolution mailing list