Swift 枚举

前端之家收集整理的这篇文章主要介绍了Swift 枚举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 枚举的定义
enum Day {
    case sunday
    case monday
    case tuesday
    case wednesday
    case thursday
    case friday
    case saturday
}

let day = Day.monday
func getDayStatus(day:Day)->Void {
    switch day {
    case Day.sunday,Day.saturday:
        print("Rest Day")
        break

    default:
        print("Work Day")
        break
        
    }
}

getDayStatus(day: day)


给枚举附上原始值

// 枚举的定义,给枚举附上原始值
enum Day: Int {
    case sunday = 0
    case monday = 1
    case tuesday = 2
    case wednesday = 3
    case thursday = 4
    case friday = 5
    case saturday = 6
}

func daysBeforeNewWeek(day:Day) ->Int {
    return 7 - day.rawValue
}
daysBeforeNewWeek(day: Day.monday) // 离新的星期还有几天

枚举可以有方法,这就厉害了我的Swift

// 枚举的定义,给枚举附上原始值
enum Day: Int {
    case sunday = 0
    case monday = 1
    case tuesday = 2
    case wednesday = 3
    case thursday = 4
    case friday = 5
    case saturday = 6
    
    func isWorkDay() -> Bool {
        switch self {
        case .monday,.tuesday,.wednesday,.thursday,.friday:
            return true
        default:
            return false
        }
    }
}

var day = Day.friday
day.isWorkDay()

猜你在找的Swift相关文章