Swift中生成指定区间数值数组的技术实现咨询
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
xor manually append elements - Safer: Using
letinstead ofvar(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

