Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

how to use array.count in swift for-in loop

I'm a beginner in swift (probably) and I am learning how to use arrays I was trying to make a for-in loop with a loop amount of 1...array.count, but instead I get an error of:

Fatal error: Index out of range Current stack trace: 0
libswiftCore.so 0x00007f0f71f0aea0 swift_reportError + 50 1 libswiftCore.so
0x00007f0f71f7c0c0 swift_stdlib_reportFatalError + 69 2
libswiftCore.so 0x00007f0f71e775d7 + 3347927 3 libswiftCore.so 0x00007f0f71c94d80 fatalErrorMessage(:
:file:line:flags:) + 19 4 libswiftSwiftOnoneSupport.so 0x00007f0f755c7ad0 specialized Array.subscript.getter + 85 6 swift
0x00000000004f23c9 + 992201 7 swift
0x00000000004f6a40 + 1010240 8 swift
0x00000000004e62ef + 942831 9 swift
0x00000000004d5093 + 872595 10 swift
0x00000000004d0e4e + 855630 11 swift
0x0000000000473c16 + 474134 12 libc.so.6
0x00007f0f73771ab0 __libc_start_main + 231 13 swift
0x000000000047387a + 473210 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret Forecast.swift -disable-objc-interop -module-name Forecast /usr/bin/swift[0x4521834] /usr/bin/swift[0x451f48e] /usr/bin/swift[0x4521c48] /lib/x86_64-linux-gnu/libpthread.so.0(+0x128a0)[0x7f0f7532b8a0] /usr/lib/swift/linux/libswiftCore.so(+0x3315d7)[0x7f0f71e775d7] /usr/lib/swift/linux/libswiftCore.so($ss18_fatalErrorMessage__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtF+0x13)[0x7f0f71c94d93] /usr/lib/swift/linux/libswiftSwiftOnoneSupport.so($sSayxSicigSi_Tg5+0x55)[0x7f0f755c7b25] [0x7f0f7575d315] /usr/bin/swift[0x4f23c9] /usr/bin/swift[0x4f6a40] /usr/bin/swift[0x4e62ef] /usr/bin/swift[0x4d5093] /usr/bin/swift[0x4d0e4e] /usr/bin/swift[0x473c16] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x7f0f73771b97] /usr/bin/swift[0x47387a]

what do I do? Here is my code, it is for CodeAcademy:

var temperature: [Int] = [66, 68, 72, 76, 80, 82, 85, 85, 84, 82, 81, 78, 74, 73, 72, 71, 70, 69, 68, 65, 63, 62, 61, 63]

// Write your code below ??
for i in 1...temperature.count{
  print(temperature[i])
}
question from:https://stackoverflow.com/questions/65944217/how-to-use-array-count-in-swift-for-in-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I presume your goal is to print all the temperature elements. Change

for i in 1...temperature.count {

To

for i in 0..<temperature.count {

Array indexes start at zero and end at one less than the count. The ..< operator handles this nicely. Or, even better, say

for i in temperature.indices {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...