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

Swift中生成指定区间数值数组的技术实现咨询

Optimizing the Range Array Generation in Your Swift Function

Hey there! Let's clean up that array generation part of your Swift function—right now you're using a manual while loop to build the array from m to n, but Swift has built-in, more efficient ways to handle this that are also way easier to read.

The Simplest Fix: Use a Closed Range + Array Initializer

Instead of manually incrementing a variable and appending to the array, you can directly create an array from a closed range (which includes both the start and end values) with one line of code:

let z = Array(m...n)

This does exactly what your original loop does—generates an array containing every integer from m to n inclusive—but it's:

  • More concise: No need to manage extra variables like x or manually append elements
  • Safer: Using let instead of var (since you don't need to modify the array right now) prevents accidental changes
  • More efficient: Swift's range-to-array conversion is optimized under the hood, better than a hand-written loop for most cases

Updated Full Function

Here's how your function looks with this optimization:

func step(_ g: Int, _ m: Int, _ n: Int) -> (Int, Int)? { 
    // Generate array of numbers from m to n (inclusive) in one line
    let z = Array(m...n) 
    
    // Your future prime-checking logic can stay/expand here
    for i in z { 
        var k = 2 
        while k < n { 
            if i % k != 0 && i != k { 
                // Add your prime validation logic here later
            } 
            k += 1 
        } 
    } 
    
    print(z) 
    return (0, 0) 
}

Bonus: Skip the Array Entirely (If Possible)

If you only need to iterate over the numbers from m to n (and don't need to store the entire array for later use), you can skip creating the array entirely and loop directly over the range:

func step(_ g: Int, _ m: Int, _ n: Int) -> (Int, Int)? { 
    // Iterate directly over the range—no array needed!
    for i in m...n { 
        var k = 2 
        while k < n { 
            if i % k != 0 && i != k { 
                // Add your prime validation logic here later
            } 
            k += 1 
        } 
    } 
    
    // If you still need to print the range as an array, you can convert it here
    print(Array(m...n))
    return (0, 0) 
}

This saves memory, especially if n - m is a large number, since you're not storing all the values in an array at once.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:06:37