Skip to content

Instantly share code, notes, and snippets.

@antonio081014
Last active January 31, 2017 17:25
Show Gist options
  • Save antonio081014/e2b7aeb32639e4d6e3eb7d82a1f531d8 to your computer and use it in GitHub Desktop.
Save antonio081014/e2b7aeb32639e4d6e3eb7d82a1f531d8 to your computer and use it in GitHub Desktop.
This is a simple OptionSet Demo in swift.

This is a simple OptionSet Demo written in swift.

import UIKit

struct Weekday: OptionSet, CustomStringConvertible {
    let rawValue: Int
    
    /// Monday
    static let Monday = Weekday(rawValue: 1 << 2)
    /// Tuesday
    static let Tuesday = Weekday(rawValue: 1 << 3)
    /// Wednesday
    static let Wednesday = Weekday(rawValue: 1 << 4)
    /// Thursday
    static let Thursday = Weekday(rawValue: 1 << 5)
    /// Friday
    static let Friday = Weekday(rawValue: 1 << 6)
    /// Saturday
    static let Saturday = Weekday(rawValue: 1 << 7)
    /// Sunday
    static let Sunday = Weekday(rawValue: 1 << 1)
    
    /// Weekday from Sunday to Saturday in an Array.
    static let WeekInArray: [Weekday] = [.Sunday, .Monday, .Tuesday, .Wednesday, .Thursday, .Friday, .Saturday]
    
    /// Weekday constant contains Sunday through Saturday.
    static let Week: Weekday = [.Sunday, .Monday, .Tuesday, .Wednesday, .Thursday, .Friday, .Saturday]
    
    var weekdayInCalendar: Int {
        return Int(log2(Double(self.rawValue)))
    }
    
    /// A textual representation of this instance.
    /// Using the first 3 characters of each enum case to present its textual meaning.
    var description: String {
        get {
            switch self {
            case Weekday.Monday:
                return "Mon"
            case Weekday.Tuesday:
                return "Tue"
            case Weekday.Wednesday:
                return "Wed"
            case Weekday.Thursday:
                return "Thu"
            case Weekday.Friday:
                return "Fri"
            case Weekday.Saturday:
                return "Sat"
            case Weekday.Sunday:
                return "Sun"
            default:
                return "Unknown"
            }
        }
    }
}

print("\(Weekday.Monday)")
print("\(Weekday.Week)")
print("\(Weekday.WeekInArray)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment