如何将从枚举中接收的值转换为Swift中的String?

时间:2015-07-27 23:17:26

标签: swift enums

我在Swift中创建了以下代码。当我运行它时,我会得到类似的东西:

今天是(枚举价值)   周一和周三的班级是CIS 110

我想得到的是当天的名字(例如,"星期一和#34;)。当我在调试模式下运行代码并观察变量时,"工作日",我看到了星期几。但是,当代码完成运行时,我最终会得到"(枚举值)"。

代码:

import Foundation
import Darwin


//weekdays
enum Weekdays: Int{
    case Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

//get random day of the week
func getDay() ->Int{
    let day = Int(1 + arc4random_uniform(7)) //random number 1 - 7
    return day
}


//determine schedule
var schedule: String = ""

func getSchedule(day: Int) -> String {
    switch day{
    case 1, 3:
        schedule = "Monday and Wednesday's class is CIS 110"
    case 2, 4:
        schedule = "Tuesday and Thursday's classes are ENG 111 and PSY 150"
    default:
        schedule = "It's the weekend! Have fun!"
    }
    return schedule
}
let day = getDay()
//take that random day and use the number the rawValue of the 
//Weekdays to get the weekday
let weekday = Weekdays(rawValue: day)!

println("Today is \(weekday)")
println(getSchedule(day))

1 个答案:

答案 0 :(得分:0)

采用Printable(在Swift 2.0中称为CustomStringConvertible)并实现description覆盖,以实现您的目标。