I'm new to programming and having a hard time coming up with an efficient way to create an array of times without typing out the entire array in swift.
I would like to dynamically create an array of the form:
["5:00","5:30", (...), "22:00"]
Here's what I have so far:
var timeSlots = [Double]()
var firstTime: Double = 5
var lastTime: Double = 22 // 10pm
var slotIncrement = 0.5
var numberOfSlots = Int((lastTime - firstTime) / slotIncrement)
var i: Double = 0
while timeSlots.count <= numberOfSlots {
timeSlots.append(firstTime + i*slotIncrement)
i += 1
}
print(timeSlots) // [5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0, 16.5, 17.0, 17.5, 18.0, 18.5, 19.0, 19.5, 20.0, 20.5, 21.0, 21.5, 22.0]
The time interval portion is important because I would like to be able to create an array with 15 minute times slots, 10 minute time slots, etc.
You just need to multiply your time slots elements by 60 to convert your number of hours to minutes and use DateComponentsFormatter
using .positional
unitsStyle to convert the TimeInterval
(seconds) to String
:
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = .positional
let times = timeSlots.flatMap{dateComponentsFormatter.string(from: $0 * 60)}
print(times) // ["5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00", "9:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00"]
Note that the result means actually minutes and seconds but the string representation it is exactly what you want.
Another option is to use String(format:)
initializer and create a custom format to convert your number of hours as follow:
extension Double {
var hours2Time: String {
return String(format: "%02d:%02d", Int(self), Int((self * 60).truncatingRemainder(dividingBy: 60)))
// or formatting the double with leading zero and no fraction
// return String(format: "%02.0f:%02.0f", rounded(.down), (self * 60).truncatingRemainder(dividingBy: 60))
}
}
let times2 = timeSlots.map{ $0.hours2Time }
print(times2) // // ["05:00", "05:30", "06:00", "06:30", "07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00"]