使用关联值时,如何显示枚举的关联值?
enum dayOfWeek{
case Monday(String)
case Tuesday(String)
case Wednesday(String)
}
以下失败:
var someDay = dayOfWeek.Wednesday("Wednesday-4")
println(someDay.rawValue)
另外,有没有办法在使用关联值创建枚举期间初始化枚举?例如:
enum dayOfWeek{
case Monday(String: "Monday-2")
case Tuesday(String: "Tuesday-3")
case Wednesday(String: "Wednesday-4")
}
答案 0 :(得分:2)
您可能会将原始值与关联值混淆。您可以将枚举案例的原始值视为案例所代表的基础值。如果这是您想要的,您可以这样指定:
enum DayOfWeek : String {
case Monday = "Monday"
case Tuesday = "Tuesday"
case Wednesday = "Wednesday"
// ...
}
String
是原始值类型,"Monday"
,"Tuesday"
等是原始值,可以像这样访问:
let day = DayOfWeek.Monday
println(day.rawValue) // "Monday"
另一方面,关联值是与枚举案例的特定实例关联的其他值。问题中的代码使用关联值,因此您在创建每个特定实例时都要指定一个值:
enum DayOfWeek {
case Monday(String)
case Tuesday(String)
case Wednesday(String)
// ...
}
let day = DayOfWeek.Monday("The worst")
但是,如果没有switch
语句,则无法提取该值:
switch day {
case .Monday(let description):
println(description)
default:
break
}
答案 1 :(得分:0)
enum dayOfWeek: String{
case Monday = "Monday-2", Tuesday = "Tuesday-3"
}
OtherDay.Monday.rawValue
dayOfWeek
是一个枚举,您有枚举Monday
和Tuesday
,Monday
的关联值已设置为"Monday-2"
。要获得此值,您可以使用枚举的.rawValue