![](/img/trans.png)
[英]In Swift 5, how do I efficiently extract and use elements in multidimensional arrays?
[英]How to use reduce() on multidimensional arrays in swift
我想遍歷一個多維數組並將元素相互比較並在滿足條件時增加一個值
var arrayExample = [[4,8],[15,30],[25,50]];
var noOfSimiRect: Int = 0
arrayExample.reduce(0) {
let a = $0[0] //error: Value of type 'int' has no subscripts
let b = $0[1] //error: Value of type 'int' has no subscripts
let c = $1[0]
let d = $1[1]
if a.isMultiple(of: c) && b.isMultiple(of: d) {
noOfSimiRect += 1
}
}
print(noOfSimiRect)
或者,如果我使用以下語法,我仍然會在那里收到錯誤
var arrayExample = [[4,8],[15,30],[25,50]];
var noOfSimiRect: Int = 0
arrayExample.reduce(0) {
let a = $0.0 //error: value of type 'int' has no member '0'
let b = $1.0 //error: value of type 'int' has no member '1'
let c = $0.0 //error: value of type '[int]' has no member 0'
let d = $1.0 //error: value of type '[int]' has no member '1'
if a.isMultiple(of: c) && b.isMultiple(of: d) {
noOfSimiRect += 1
}
}
print(noOfSimiRect)
感謝 David 和 Martin 回答我的問題,但我在您的兩個解決方案中都發現了一個問題。
var arrayExample = [[4,8],[15,30],[25,50]];
在給定的數組中,我想要以下內容:
您似乎誤解了reduce
關閉的輸入。 第一個輸入參數是累加結果,而第二個是數組的當前元素。 $0
和$1
不是您假設的數組的當前元素和下一個元素。
您需要遍歷數組的indices
以訪問 2 個后續嵌套的 arrays 並能夠相互檢查它們的元素。
var noOfSimiRect: Int = 0
for index in arrayExample.indices.dropLast() {
let current = arrayExample[index]
let next = arrayExample[index + 1]
if current[0].isMultiple(of: next[0]) && current[1].isMultiple(of: next[1]) {
noOfSimiRect += 1
}
}
print(noOfSimiRect)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.