Day of the week. From String to int

Is it possible to convert a var with the day of the week to a number? (and the other way around)

let diaSetmana = "Monday" let diaSetmana2 = 2

I know how to convert from date(): let date = Date() let calendar = Calendar.current let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" let dayString = dateFormatter.string(from: date)

I am asking for converting not from date() but from a var that I have a random day of the week

Accepted Reply

converting from a var that I have a random day of the week

Will this var contain a string with the name of the day ?

If I understand your question properly, a simple dictionary will do it

let sunday = "sunday"    // So that you can localize
let monday = "monday"
// and so on

let dayNumbers = [sunday: 1, monday: 2]  // etc

then when you get a String value in var,

let value = "Monday"
if let numOfDay = dayNumbers[value.lowercased()] { } // lowercased to cope with any capitalisation.

Replies

converting from a var that I have a random day of the week

Will this var contain a string with the name of the day ?

If I understand your question properly, a simple dictionary will do it

let sunday = "sunday"    // So that you can localize
let monday = "monday"
// and so on

let dayNumbers = [sunday: 1, monday: 2]  // etc

then when you get a String value in var,

let value = "Monday"
if let numOfDay = dayNumbers[value.lowercased()] { } // lowercased to cope with any capitalisation.