Как объединить NSArray в NSMutableArray в Swift? - PullRequest
0 голосов
/ 23 мая 2018

В моем приложении я хочу объединить NSArray с NSMutable Array на основе некоторого сценария (т. Е.) Если accountNumber и Fips совпадают в обоих массивах, я хочу объединить, как в следующем формате.

Здесь я вставляюМой ответ NSArray:

{
    AccountNumber = G110080003900;
    City = JACKSON;
    FIPS = 39079;
    InspectionId = 425;
    InspectionLogId = 366;
    InspectionType = "OCA Inspector";
    InspectionTypeId = 2;
    LandUseCode = 1001;
    ScheduledDate = "2018-05-21T00:00:00";
    State = OH;
    Status = Done;
    StatusId = 2;
    StreetName = "JISCO WEST";
    StreetNumber = 4564;
    TemplateId = 1075;
    TemplateName = "AVM Inspection";
    UserId = 51;
    UserPropertyId = 1546;
    XCoordinate = "39.03665";
    YCoordinate = "-82.6797";
    Zip = 45640;
},
    {
    AccountNumber = 000053809;
    City = 0;
    FIPS = 5051;
    InspectionId = 427;
    InspectionLogId = 368;
    InspectionType = "OCA Inspector";
    InspectionTypeId = 2;
    LandUseCode = 8001;
    ScheduledDate = "2018-05-22T00:00:00";
    State = AR;
    Status = Done;
    StatusId = 2;
    StreetName = CYPRESSVALE;
    StreetNumber = 0;
    TemplateId = 1075;
    TemplateName = "AVM Inspection";
    UserId = 51;
    UserPropertyId = 1547;
    XCoordinate = 0;
    YCoordinate = 0;
    Zip = 0;
},
    {
    AccountNumber = 000053809;
    City = 0;
    FIPS = 5051;
    InspectionId = 428;
    InspectionLogId = 369;
    InspectionType = "OCA Inspector";
    InspectionTypeId = 2;
    LandUseCode = 8001;
    ScheduledDate = "2018-05-23T00:00:00";
    State = AR;
    Status = "In Progress";
    StatusId = 4;
    StreetName = CYPRESSVALE;
    StreetNumber = 0;
    TemplateId = 1075;
    TemplateName = "AVM Inspection";
    UserId = 51;
    UserPropertyId = 1547;
    XCoordinate = 0;
    YCoordinate = 0;
    Zip = 0;
},{
    AccountNumber = "633-342-004";
    City = "INDIAN WELLS";
    FIPS = 6065;
    InspectionId = 349;
    InspectionLogId = 290;
    InspectionType = "OCA Inspector";
    InspectionTypeId = 2;
    LandUseCode = 1001;
    ScheduledDate = "2018-03-19T00:00:00";
    State = CA;
    Status = Completed;
    StatusId = 3;
    StreetName = CHEYENNE;
    StreetNumber = 77431;
    TemplateId = 1090;
    TemplateName = "Casualty Loss Inspection";
    UserId = 51;
    UserPropertyId = 1482;
    XCoordinate = "33.72453";
    YCoordinate = "-116.313739";
    Zip = 92210;
},

)

Здесь я вставляю Мой ответ NSMutableArray:

{
    AccountNumber = 000053809;
    AssessmentRollId = "<null>";
    AssessmentYear = 0;
    BuildingArea = 0;
    City = 0;
    CreatedBy = 51;
    DateCreated = "2018-05-21T00:01:47.93";
    DateModified = "2018-05-21T00:01:47.93";
    FIPS = 5051;
    Id = 1547;
    LandUseCode = 8001;
    LotSizeSquareFeet = 0;
    PropertyId = 78781545;
    State = AR;
    StreetName = CYPRESSVALE;
    StreetNumber = 0;
    TotalAssessedValue = 600;
    UpdatedBy = 51;
    UserId = 51;
    XCoordinate = 0;
    YCoordinate = 0;
    YearBuilt = 0;
    Zip = 0;
},
    {
    AccountNumber = "<null>";
    AssessmentRollId = "<null>";
    AssessmentYear = "<null>";
    BuildingArea = "<null>";
    City = Houston;
    CreatedBy = 51;
    DateCreated = "2018-05-22T01:14:43.29";
    DateModified = "2018-05-22T01:14:43.29";
    FIPS = 48201;
    Id = 1548;
    LandUseCode = 338;
    LotSizeSquareFeet = 2525;
    PropertyId = 1;
    State = TX;
    StreetName = "san Felipe suite 2600";
    StreetNumber = 5847;
    TotalAssessedValue = "<null>";
    UpdatedBy = 51;
    UserId = 51;
    XCoordinate = "29.749522";
    YCoordinate = "-95.481959";
    YearBuilt = 2013;
    Zip = 77057;
}

Если AccountNumber и Fips одинаковы в обоих массивах, я хочу добавитьКонкретный индекс для дочернего массива для значения NSMutableArray.Здесь я показываю формат, в котором я хочу объединить оба массива. Предположим, что AccountNumber и Fips не совпадают, значит просто я хочу добавить определенный индекс в NSMutableArray в качестве нового словарного индекса .:

{
    AccountNumber = 000053809;
    AssessmentRollId = "<null>";
    AssessmentYear = 0;
    BuildingArea = 0;
    City = 0;
    CreatedBy = 51;
    DateCreated = "2018-05-21T00:01:47.93";
    DateModified = "2018-05-21T00:01:47.93";
    FIPS = 5051;
    Id = 1547;
    Inspectionlist =         (
        {
            AccountNumber = 000053809;
            City = 0;
            FIPS = 5051;
            InspectionId = 428;
            InspectionLogId = 369;
            InspectionType = "OCA Inspector";
            InspectionTypeId = 2;
            LandUseCode = 8001;
            ScheduledDate = "2018-05-23T00:00:00";
            State = AR;
            Status = "In Progress";
            StatusId = 4;
            StreetName = CYPRESSVALE;
            StreetNumber = 0;
            TemplateId = 1075;
            TemplateName = "AVM Inspection";
            UserId = 51;
            UserPropertyId = 1547;
            XCoordinate = 0;
            YCoordinate = 0;
            Zip = 0;
        },
        {
            AccountNumber = 000053809;
            City = 0;
            FIPS = 5051;
            InspectionId = 428;
            InspectionLogId = 369;
            InspectionType = "OCA Inspector";
            InspectionTypeId = 2;
            LandUseCode = 8001;
            ScheduledDate = "2018-05-23T00:00:00";
            State = AR;
            Status = "In Progress";
            StatusId = 4;
            StreetName = CYPRESSVALE;
            StreetNumber = 0;
            TemplateId = 1075;
            TemplateName = "AVM Inspection";
            UserId = 51;
            UserPropertyId = 1547;
            XCoordinate = 0;
            YCoordinate = 0;
            Zip = 0;
        }
    );
    LandUseCode = 8001;
    LotSizeSquareFeet = 0;
    PropertyId = 78781545;
    State = AR;
    StreetName = CYPRESSVALE;
    StreetNumber = 0;
    TotalAssessedValue = 600;
    UpdatedBy = 51;
    UserId = 51;
    XCoordinate = 0;
    YCoordinate = 0;
    YearBuilt = 0;
    Zip = 0;
},
{
    AccountNumber = "<null>";
    AssessmentRollId = "<null>";
    AssessmentYear = "<null>";
    BuildingArea = "<null>";
    City = Houston;
    CreatedBy = 51;
    DateCreated = "2018-05-22T01:14:43.29";
    DateModified = "2018-05-22T01:14:43.29";
    FIPS = 48201;
    Id = 1548;
    LandUseCode = 338;
    LotSizeSquareFeet = 2525;
    PropertyId = 1;
    State = TX;
    StreetName = "san Felipe suite 2600";
    StreetNumber = 5847;
    TotalAssessedValue = "<null>";
    UpdatedBy = 51;
    UserId = 51;
    XCoordinate = "29.749522";
    YCoordinate = "-95.481959";
    YearBuilt = 2013;
    Zip = 77057;
},{
    AccountNumber = "633-342-004";
    City = "INDIAN WELLS";
    FIPS = 6065;
    InspectionId = 349;
    InspectionLogId = 290;
    InspectionType = "OCA Inspector";
    InspectionTypeId = 2;
    LandUseCode = 1001;
    ScheduledDate = "2018-03-19T00:00:00";
    State = CA;
    Status = Completed;
    StatusId = 3;
    StreetName = CHEYENNE;
    StreetNumber = 77431;
    TemplateId = 1090;
    TemplateName = "Casualty Loss Inspection";
    UserId = 51;
    UserPropertyId = 1482;
    XCoordinate = "33.72453";
    YCoordinate = "-116.313739";
    Zip = 92210;
}

Здесь япоказать мой код Что я пробовал, я допустил какую-то ошибку, но не смог ее найти.Пожалуйста, помогите мне решить проблему.

func removeDuplicatesFromOrdersArray3() {
    print(propertyMutableArray.count)
    let storedArray = NSMutableArray()
    for a in 0..<propertyMutableArray.count {
        let orderFipsValue:NSNumber = (propertyMutableArray[a] as AnyObject).value(forKey: "FIPS") as! NSNumber
        let orderAccountNumberValue:String = (propertyMutableArray[a] as AnyObject).value(forKey: "AccountNumber") as? String ?? ""
        for b in 0..<mergeOrdersMutArray.count {
            let FipsValue:NSNumber = (mergeOrdersMutArray[b] as AnyObject).value(forKey: "FIPS") as! NSNumber
            let AccountNumberValue:String = (mergeOrdersMutArray[b] as AnyObject).value(forKey: "AccountNumber") as? String ?? ""
            if orderFipsValue == FipsValue && orderAccountNumberValue == AccountNumberValue {
                storedArray.add(mergeOrdersMutArray[b])
                let dictMutableCopy = propertyMutableArray[a] as! NSDictionary
                let editDict = NSMutableDictionary(dictionary: dictMutableCopy)
                editDict.setValue(storedArray, forKey: "Inspectionlist")
                propertyMutableArray.add(editDict)
                mergeOrdersMutArray.remove(b)
                isDuplicate = true
            }
            else {
                if (!isDuplicate) {
                    propertyMutableArray.add(mergeOrdersMutArray[b])
                }
            }
        }
    }
    print(mergeOrdersMutArray.count)
    print(propertyMutableArray.count)
    print(openOrderArray.count)
    print(logOrderArray.count)
    print(storedArray.count)
}

Ответы [ 2 ]

0 голосов
/ 07 августа 2019

Swift 5 Простой способ https://stackoverflow.com/a/57389179/6881070

https://stackoverflow.com/a/57389179/6881070 
//MARK:- Follow this link
0 голосов
/ 25 мая 2018

Я предполагаю, что вы хотите использовать эти массивы для отображения данных на некоторых экранах.Будет проще, если вы создадите классы моделей для объектов массива.

Struct NonMutableModel {
    var accntNum: String?
    var flips: Int?
    ......
}

Struct MutableModel {    
    var accntNum: String?    
    var flips: Int?    
    var inspectionList: [Model]    
    ....    
}

Инициализируйте модели с данными из ваших массивов и сохраните их в некоторых переменных.

var nonMutableModels: [NonMutableModel]?
var mutableModels: [MutableModel]?

теперь выцикл по массивам моделей, чтобы проверить значения и добавить к mutableModels.

guard let mutables = mutableModels, let nonMutables = nonMutableModels else { return }


for mutableModel in mutables {
    for model in nonMutables {
        if mutableModel.accntNum == model.accntNum, mutableModel.flips == model.flips {
            mutableModel.inspectionList.append(model)
        }
    }
}
...