簡體   English   中英

如何在 swift 中的多維 arrays 上使用 reduce()

[英]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]];

在給定的數組中,我想要以下內容:

  1. 比較 [4,8] 與 [15,30] 和 [25,50]
  2. 將 [15,30] 與 [4,8] 和 [25,50] 進行比較
  3. 將 [25,50] 與 [4,8] 和 [15,30] 進行比較

您似乎誤解了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM