這是代碼:
func setTimeArray() {
let iStart = Int(Double(selectedStart)! * 0.01)
var index = iStart
var tempArray: Array<String> = []
print("count is ", count)
for i in 0..<self.count {
var theHours = ""
if (index == 24) {
index = 0
} else if (index == 23) {
theHours = self.parse24(theString: String(index)) " to " self.parse24(theString: "0")
} else {
theHours = self.parse24(theString: String(index)) " to " self.parse24(theString: String(index 1))
}
tempArray.insert(theHours, at: i)
index = index 1
}
self.timeArray = tempArray
}
這段代碼作業得很好,但我需要將它插入到 tempArray 的位置包裝起來,這樣它就不會添加空字串。不幸的是,當我嘗試添加 if 陳述句或將 tempArray.insert(theHours, at: i) 放在已經存在的 if 陳述句中時,出現錯誤:“Swift/Array.swift:405: Fatal error: Array index is超出范圍”
我的意思是,我實際上是在沒有 if 陳述句的情況下添加更多專案!誰能告訴我如何解決這個問題?
uj5u.com熱心網友回復:
當您查看插入函式的檔案時,它說明了有關i引數的以下內容:
i插入新元素的位置。
index必須是陣列的有效索引或等于其endIndex屬性。
您需要將元素插入現有元素index或將其添加到陣列的末尾。這可能有助于增加一個print陳述句來列印index,i并且要插入它在陣列,看看究竟是怎么回事。
uj5u.com熱心網友回復:
仍然有點令人困惑,但我想我明白你要做什么......
假設count是5...
如果是 10 點,你想要一個陣列結果:
[10:00 to 11:00]
[11:00 to 12:00]
[12:00 to 13:00]
[13:00 to 14:00]
[14:00 to 15:00]
如果是 15 點,你想要一個陣列結果:
[15:00 to 16:00]
[16:00 to 17:00]
[17:00 to 18:00]
[18:00 to 19:00]
[19:00 to 20:00]
如果是22 o'clock,您希望它“環繞”并獲得以下陣列結果:
[22:00 to 23:00]
[23:00 to 0:00]
[0:00 to 1:00]
[1:00 to 2:00]
[2:00 to 3:00]
(您的self.parse24(theString: String(index))格式可能略有不同)。
如果是這樣的話,看看這個:
var tempArray: Array<String> = []
// no need for an "i" counter variable
for _ in 0..<self.count {
var theHours = ""
// if we're at 24, set index to 0
if (index == 24) {
index = 0
}
if (index == 23) {
// if we're at 23, the string will be "23:00 to 0:00"
theHours = "23:00 to 0:00"
} else {
// the string will be "index to index 1"
theHours = "\(index):00 to \(index 1):00"
}
// don't use insert, just append the new string
//tempArray.insert(theHours, at: i)
tempArray.append(theHours)
index = index 1
}
self.timeArray = tempArray
編輯
了解為什么會收到Array index is out of range錯誤可能很重要。
您仍然沒有發布導致錯誤的代碼,但我猜它是這樣的:
for i in 0..<self.count {
var theHours = ""
if (index == 24) {
index = 0
} else if (index == 23) {
theHours = self.parse24(theString: String(index)) " to " self.parse24(theString: "0")
} else {
theHours = self.parse24(theString: String(index)) " to " self.parse24(theString: String(index 1))
}
if theHours.isEmpty {
// don't add the empty string to the array
} else {
// add it to the array
tempArray.insert(theHours, at: i)
}
index = index 1
}
所以,如果我們從22 點鐘開始,并且count等于5,你的代碼會這樣做:
i equals 0
index equals 22
theHours = "22 to 23"
insert string at [i] // i is 0
increment index
increment i
i now equals 1
index now equals 23
theHours = "23 to 0"
insert string at [i] // i is 1
increment index
increment i
i now equals 2
index now equals 24
set index to 0
theHours = ""
DON'T insert empty string
increment i
i now equals 3
index now equals 0
theHours = "0 to 1"
insert string at [i] // i is 3
*** ERROR ***
您得到超出范圍的錯誤,因為您沒有在 [2] 處插入空字串,而是i不斷增加。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/390834.html
