我是编程新手,并且很难想出一种有效的方法来创建一个时间阵列而无需在swift中输入整个数组。
我想动态创建一个表单数组:
["5:00","5:30", (...), "22:00"]
这是我到目前为止所拥有的:
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]
时间间隔部分非常重要,因为我希望能够创建一个包含15分钟时隙,10分钟时隙等的阵列。
答案 0 :(得分:2)
var timeArray: [String] = []
let firstTime: Double = 5
let lastTime: Double = 22 // 10pm
var currentTime: Double = 5
var incrementMinutes: Double = 15 // increment by 15 minutes
while currentTime <= lastTime {
currentTime += (incrementMinutes/60)
let hours = Int(floor(currentTime))
let minutes = Int(currentTime.truncatingRemainder(dividingBy: 1)*60)
if minutes == 0 {
timeArray.append("\(hours):00")
} else {
timeArray.append("\(hours):\(minutes)")
}
}
答案 1 :(得分:0)
您只需将时段元素乘以60即可将您的小时数转换为分钟数,并使用DateComponentsFormatter
unitsStyle将.positional
转换为TimeInterval
(秒) 1}}:
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"]
初始值设定项并创建自定义格式以转换您的小时数,如下所示:
String(format:)
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))
}
}