young
(rtSwift)
1
I was hoping enum case assoc'ed value can have default like func parameter. Didn't find that but:
enum Foo {
case a(Int = 1) // what's this? why is .a => (Int) -> Foo
}
let x = Foo.a
print("type(of: x):", type(of: x), ", x:", x) // type(of: x): (Int) -> Foo , x: (Function)
let y = x(123)
print("type(of: y):", type(of: y), ", y:", y) // type(of: y): Foo , y: a(123)
Don't see this cover in the language guide enum section: Enumerations — The Swift Programming Language (Swift 5.7)
So why is .a is a closure? What's this useful for?
And for my original question: can enum case associated value have default?
mayoff
(Rob Mayoff)
2
When you declare a case with no associated values, you essentially get a static var:
enum Foo {
case a
// is equivalent to
static var a: Self { ... }
}
But when you declare a case with associated values, you essentially declare a static func:
enum Foo {
case a(Int = 1)
// is equivalent to
static func a(_ argument: Int = 1) -> Self { ... }
}
And so when there are associated values, you must use a as a function:
Foo.a() // use the default value
Foo.a(123) // use an explicit value
4 Likes