swift - 如何在 Swift 中将从枚举接收到的值转换为字符串?

标签 swift enums

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

今天是(枚举值) 周一和周三的类(class)是 CIS 110

我要获取的是日期的名称(例如“星期一”)。当我在 Debug模式下运行代码并观察变量“weekday”时,我看到了星期几。但是,当代码完成运行时,我以“(枚举值)”结束。

代码:

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))

最佳答案

采用 Printable(在 Swift 2.0 中称为 CustomStringConvertible)并实现一个 description 重写来执行您想要的操作。

关于swift - 如何在 Swift 中将从枚举接收到的值转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664917/

相关文章:

Java 枚举 : Gathering info from another enums

ios - (Swift) fatal error : Index out of range

swift - 在 Swift 4 中将视频旋转 90 度

ios - Swift 4 在 UITableView 中显示来自 api 的图像的正确方法

ios - 使用 Swift 的 iOS 代码结构,所有代码放在哪里?

swift - 通过 Collection View cell 在 ViewController 之间传递数据

java - 枚举超过静态初始化程序的 65535 字节限制......最好做什么?

java获取枚举中最长的字符串

java - 如何从 Java 中分配给它们的值中检索枚举常量?

java - 以不同的方式将枚举映射到 Spring 形式选择