我要做的是创建一个由数组组成的可编辑日历。
首先我创建一些变量:
import UIKit
/////////////////////////////////////////////////////////////////////
// Variables
var userName = "String"
var bedTime: Int = 0
var wakeTime: Int = 7
var sleepMonth = "String"
var quantifiedMonth: Int = 1
然后通过多维数组的日历:
var day0: [Int] = [0]
var day1: [Int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
var day2: [Int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
var day3: [Int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
var day4: [Int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
var month0 = [[0]]
var january = [day0, day1, day2, day3, day4]
var february = [day0, day1, day2, day3, day4]
var march = [day0, day1, day2, day3, day4]
var april = [day0, day1, day2, day3, day4]
var may = [day0, day1, day2, day3, day4]
var june = [day0, day1, day2, day3, day4]
var july = [day0, day1, day2, day3, day4]
var august = [day0, day1, day2, day3, day4]
var september = [day0, day1, day2, day3, day4]
var october = [day0, day1, day2, day3, day4]
var november = [day0, day1, day2, day3, day4]
var december = [day0, day1, day2, day3, day4]
var calendar = [month0, january, february, march, april, may, june, july, august, september, october, december]
然后我尝试使用嵌套的for循环来让用户说出他们通常睡着的时间:
@IBAction func setVariablesButton(_ sender: UIButton)
{
bedTime = Int(bedTimeTextField.text!)!
wakeTime = Int(wakeTimeTextField.text!)!
quantifiedMonth = Int(monthToEditTextField.text!)!
var hourX = bedTime
var hourZ = wakeTime
var dayX = 1
let dayZ = 1
let lengthMonth = calendar[quantifiedMonth].count
for _ in 1...lengthMonth // Do the following for as many days
// as are in the month
{
for _ in calendar[1][dayX][hourX]...calendar[1][dayX][24]
{
calendar[1][dayX][hourX] = 0 // Loops by amount
hourX = hourX + 1 // specified 2 lines above
}
for _ in calendar[1][dayZ][0]...calendar[1][dayZ][hourZ]
{
calendar[1][dayX][hourZ] = 0
hourZ = hourZ - 1
}
dayX = dayX + 1 // Loops by amount specified 8 lines above
}
bedTimeLabel.text = "\(calendar[1][1])"
}
当我在建造时,我总是有
var quantifiedMonth
设置为0,允许程序工作。然后我意识到,如果我将它设置为1,那么它会中断。由于我在程序运行时得到的输出,我无法解决原因。
说我有
var quantifiedMonth = 0
bedTime = 20
wakeTime = 7
然后我的输出将是
[0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0]
但
时var quantifiedMonth = 1
程序崩溃了。我无法理解为什么会这样。在我看来,我不能在
时获得我做的输出var quantifiedMonth = 0
请帮忙。我试图彻底解决我的问题,但如果我对某事感到含糊,请告诉我。
答案 0 :(得分:0)
问题是你在for循环之外声明了应该在其中声明的变量。
var hourX = bedTime
var hourZ = wakeTime
应该这样声明:
for _ in 1...lengthMonth
{
var hourX = bedTime
var hourZ = wakeTime
否则这些变量不会像它们应该那样设置。
您还需要将lengthMonth更改为
let lengthMonth = calendar[quantifiedMonth].count - 1
因为你的数组从0开始,你的for循环开始为1.否则你会得到一个“索引超出范围”的错误。