gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:02:25 28 4
gpt4 key购买 nike

我在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com