Reputation: 44332
When using associated values, how do you display the associated value of an enum?
enum dayOfWeek{
case Monday(String)
case Tuesday(String)
case Wednesday(String)
}
The following fails:
var someDay = dayOfWeek.Wednesday("Wednesday-4")
println(someDay.rawValue)
Also, is there a way to initialize the enum during its creation using associated values? For example:
enum dayOfWeek{
case Monday(String: "Monday-2")
case Tuesday(String: "Tuesday-3")
case Wednesday(String: "Wednesday-4")
}
Upvotes: 0
Views: 656
Reputation: 93276
You might be confusing raw values with associated values. You can think of an enum case's raw value as the underlying value that the case represents. If that's what you want, you'd specify it like this:
enum DayOfWeek : String {
case Monday = "Monday"
case Tuesday = "Tuesday"
case Wednesday = "Wednesday"
// ...
}
String
is the raw value type, and "Monday"
, "Tuesday"
, etc. are the raw values, which can be accessed like this:
let day = DayOfWeek.Monday
println(day.rawValue) // "Monday"
Associated values, on the other hand, are additional values that are associated with a particular instance of an enum case. The code in the question uses associated values, so you'd be specifying a value when you create each particular instance:
enum DayOfWeek {
case Monday(String)
case Tuesday(String)
case Wednesday(String)
// ...
}
let day = DayOfWeek.Monday("The worst")
However, you can't extract that value without a switch
statement:
switch day {
case .Monday(let description):
println(description)
default:
break
}
Upvotes: 2
Reputation: 5083
enum dayOfWeek: String{
case Monday = "Monday-2", Tuesday = "Tuesday-3"
}
OtherDay.Monday.rawValue
dayOfWeek
is a enum, you have the enum’s Monday
and Tuesday
, the associated value of Monday
has been set to "Monday-2"
. To get this value you could use the .rawValue
of the enum
Upvotes: 0