Search code examples
swiftmergensarraynsmutablearray

Merge two NSMutableArray in Swift


I have two NSMutableArray:

let value = data as NSDictionary
                let array_item : NSArray! = (value.value(forKey: "mids") as! NSArray)
                if let array = array_item {
                    let array_list : NSMutableArray! =  NSMutableArray(array:array)
                    let array_list_checksum : NSMutableArray = NSMutableArray()
                    let array_list_server_version : NSMutableArray = NSMutableArray()
                    
                    for item in array_list {
                        let dic_item : NSDictionary! = item as? NSDictionary
                        if let dic = dic_item {
                            array_list_checksum.add(dic.value(forKey: "checksum")!)
                            array_list_server_version.add(dic.value(forKey: "server_version")!)
                            array_server_versions = array_list_server_version
                        }
                    }

in array_list_checksum I have strings like: "efopfkefokepre4345345345345", in array_list_server_versions I have strings like: "version 2.0 in 2018" What I need to do is merge information of each checksum and each server version in this format: "version 2.0 in 2018 checksum: efopfkefokepre4345345345345", with the "checksum" word that is not included in the array. So my problem is to merge this two NSMutableArray in Swift and how to add the word "checksum:" between the two values.


Solution

  • You have two array you want to merge:

    let array_list_checksum : NSMutableArray = NSMutableArray()
    let array_list_server_version : NSMutableArray = NSMutableArray()
    

    Use zip operator to merge arrays values into tuples of pairs. And use map operator to create merged array with format you wanted:

    let merged = zip(array_list_server_version, array_list_checksum).map{
        "\($0) checksum: \($1)"
    }
    

    Convert resulted array to NSMutableArray if you need it:

    let mergedArray = NSMutableArray(array: merged)
    

    Few notes:

    • Use swift default arrays and dictionaries, if you have swift-only project
    • CamelCase in iOS is preferred over snake_case