Swift Playground报错:无法将‘Int’类型的值赋给‘[Int]’类型,求助实现数组相邻元素乘积功能
Hey there! Let's break down what's going wrong with your code and get it working exactly how you want it to.
First, the root of the error
The message "Cannot assign value of type 'Int' to type '[Int]'" spells out the core issue clearly:
newArrayis declared as an array of integers ([Int]), butnumber[i] * number[i+1]gives you a single integer value. You can't assign a single number directly to an array—you need to add it to the array instead of overwriting it.
Second, a hidden crash waiting to happen
Your loop uses 0...number.count-1, which means when i reaches the last index of number (that's 3 for your array), number[i+1] would try to access number[4]—an index that doesn't exist. This would crash your code even if you fixed the first error.
Here's the corrected code
We'll use the append() method to add each calculated product to newArray, and adjust the loop range to avoid index out-of-bounds issues:
var number: [Int] = [1,2,3,4] var newArray: [Int] = [] // Loop from 0 up to (but not including) the second-to-last index for i in 0..<number.count-1 { let product = number[i] * number[i+1] newArray.append(product) // Add the product to the array instead of overwriting it } print(newArray) // Output: [2, 6, 12] (matches your expected 1*2, 2*3, 3*4)
A more "Swifty" approach
If you want cleaner, more idiomatic Swift code, you can skip the manual loop entirely and use built-in functions like zip and map:
let number = [1,2,3,4] let newArray = zip(number, number.dropFirst()).map(*) print(newArray) // Same output: [2, 6, 12]
Here's how this works:
number.dropFirst()creates a copy of your array without the first element:[2,3,4]zip(number, number.dropFirst())pairs elements from both arrays into tuples:(1,2), (2,3), (3,4)map(*)applies multiplication to each tuple, generating your final array of products.
内容的提问来源于stack exchange,提问作者Orhanko

