我正在尝试从数组中获取第4个项目。这些在数组下面给出:
let mainArray = ["1", "2", "3", "7", "10", "4", "5", "6", "9", "12", "16", "11", "13", "14", "15"]
let valueCheck = "3"
//check value present or not in array
if mainArray.contains(valueCheck){
//if yes print next value from match value
Let valuePresent = self.mainArray.index(after: Int(valueCheck)!)
print(valuePresent)
}
output =“ 4”
但我想要“ 7”
当我尝试上面的代码来获取第4个值时,它们给了我第4个索引,但是我想要第4个索引值。
有人可以向我解释如何解决这个问题,我已经尝试解决了这个问题,但没有结果。
任何帮助将不胜感激。
谢谢。
答案 0 :(得分:2)
let mainArray = ["1", "2", "3", "7", "10", "4", "5", "6", "9", "12", "16", "11", "13", "14", "15"]
let valueCheck = "3" // index for this is 2
//check value present or not in array
if let index = mainArray.firstIndex(of: valueCheck){
let value = mainArray[index + 1]
print(value)
}
这是可行的,例如,如果您希望“ 15”之后的项目出现,valueCheck = "15"
则会崩溃。
您可以通过以下方法扩展收集范围:
extension Collection {
subscript(safe index: Index) -> Element? {
return return index < endIndex && index >= startIndex ? self[index] : nil
}
}
然后使用以下代码更新代码:
let mainArray = ["1", "2", "3", "7", "10", "4", "5", "6", "9", "12", "16", "11", "13", "14", "15"]
let valueCheck = "3" // index for this is 2
//check value present or not in array
if let index = mainArray.firstIndex(of: valueCheck){
let value = mainArray[safe: index + 1]
print(value)
}
答案 1 :(得分:0)
首先,您必须检查索引是否未超出范围,然后可以通过数组
Subscript
来获取值,如下所示
let mainArray = ["1", "2", "3", "7", "10", "4", "5", "6", "9", "12", "16", "11", "13", "14", "15"]
let valueCheck = "3"
if let index = Int(valueCheck) {
if mainArray.count > index {
let result = mainArray[index]
}
}
希望它会对您有所帮助。
答案 2 :(得分:0)
您必须设置第三个元素的索引,即“ 7” 因为数组以零的索引开头
let mainArray = ["1", "2", "3", "7", "10", "4", "5", "6", "9", "12", "16", "11", "13", "14", "15"]
let valueCheck = "7" // index for this is 3
//check value present or not in array
if mainArray.contains(valueCheck){
//if yes print next value from match value
Let valuePresent = self.mainArray.index(after: Int(valueCheck)!)
let output = mainArray[valuePresent]
print(output) // the output will be 10
}
答案 3 :(得分:0)
def function_name():
print('placeholder')
if __name__ == '__main__':
function_name() #for eg: main()
答案 4 :(得分:0)
let mainArray = [“ 1”,“ 2”,“ 3”,“ 7”,“ 10”,“ 4”,“ 5”,“ 6”,“ 9”,“ 12”,“ 16” ,“ 11”,“ 13”,“ 14”,“ 15”]
if mainArray.indices.contains(3){ 让值= mainArray [3] 打印(值) }
此代码将为您提供帮助。