簡體   English   中英

如何比較兩個數組對象-Swift 4

[英]How do I compare two array Objects - Swift 4

我有2個[Any]類型的數組-字典對象
其他數組包含其他對象集[Any] (第二個數組對象包含在第一個數組中)

我需要找到第二個數組元素的第一個數組的索引

例如:-

let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]

let secondArray = [["key3":64],["key6":68]]

我如何找到secondArray元素的firstArray索引

let index = firstArray.index{$0 == secondArray[0]};
print("this value ", index);

將打印optional(2),基本上是2

首先,從secondArray獲取密鑰 然后,您嘗試在firstArray找到鍵的索引 請注意,如果鍵不存在,則某些值可能為nil。

let firstArray = [["key1":6],["key2":8],["key3":64],["key4":68],["key5":26],["key6":76]]
let secondArray = [["key3":64],["key6":68], ["key8": 100]]

let indexes = secondArray
    .map({ $0.first?.key }) //map the values to the keys
    .map({ secondKey -> Int? in
        return firstArray.index(where:
            { $0.first?.key == secondKey } //compare the key from your secondArray to the ones in firstArray
        )
    })

print(indexes) //[Optional(2), Optional(5), nil]

我還添加了一個示例案例,結果為零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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