You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中为何for循环会先于后续代码执行完成?

Why does a 10 million-iteration loop finish before the next print statement?

Hey Lance, great question—this is totally not a "common sense" thing if you haven't dug into how CPUs and thread execution work, so no need to apologize! Let's break this down in simple terms that fit your self-taught iOS dev background:

The core rule: Single-threaded execution order

First, every line of code in your iOS app's main thread (the one that runs your UI and most basic logic) executes in strict top-to-bottom order. There's no "skipping ahead" to run the later print("before this prints") while the loop is still running. The system won't start that final print until the entire loop has completed every iteration.

Take your code example:

for num in 1...10000000 {
    if num == 10000000 {
        print("why does this print") // 循环需迭代1000万次才会打印此内容
    }
}
print("before this prints")

The loop runs all 10 million iterations first, then the print("before this prints") line runs. No exceptions here—this is how single-threaded code works across all platforms, not just iOS.

Why 10 million iterations feel "instant"

Here's the key part you might not realize: modern CPUs are extremely fast. We're talking about billions of operations per second. Your loop is doing a tiny, tiny task each iteration:

  • Increment the num variable (a super simple arithmetic operation)
  • Check if num equals 10,000,000 (a basic comparison)
  • Only print something on the very last iteration

Even 10 million of these tiny operations only take milliseconds to finish—way too fast for you to notice any delay. It might seem like a huge number, but to a CPU, it's just a blip.

To put it in perspective: if your CPU can do 5 billion operations per second, 10 million is 0.2% of that—so it would take 0.002 seconds (2 milliseconds) to run. That's why it feels like the loop finishes instantly, then the final print runs right after.

What would make the loop slow down?

If your loop had a more complex task each iteration—like loading data from the internet, processing an image, or doing heavy mathematical calculations—then it would take noticeable time, and you'd see the final print wait. But in your example, it's just basic integer checks and increments, which are the kind of operations CPUs are built to handle lightning-fast.

A quick note on Xcode/SDKs

You mentioned that Xcode's SDK handles low-level logic, and that's true—but this behavior isn't specific to Xcode or iOS. Every single-threaded program (no matter the language or platform) follows this top-to-bottom execution rule. The SDK doesn't change that; it just hides the lower-level details of how the CPU runs those operations.


内容的提问来源于stack exchange,提问作者Lance Samaria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:18:33