iosobjective-cswiftnsmutablearray

How to form static data with the structure like array of objects in swift 4?


Currently, I'm building an app using the Swift platform. I need to show static data like an array of objects structure because I need to load data on UITableView section and rows. Below is the example array of objects structure in objective C. I need to replicate the same thing in Swift.

NSArray *dummyArray = [[NSArray alloc] initWithObjects:
                       [[NSDictionary alloc] initWithObjectsAndKeys:@"India",@"team",@"280",@"score",@"5",@"wickets", nil],
                       [[NSDictionary alloc] initWithObjectsAndKeys:@"SouthAfrica",@"team",@"279",@"score",@"9",@"wickets", nil],
                       nil];

NSMutableArray *demoArrayOfObjects = [[NSMutableArray alloc] initWithObjects:
                                      [[NSDictionary alloc] initWithObjectsAndKeys:@"17-03-2018",@"date",@"Ind win by 5 wickets",@"result",@"SouthAfrica",@"Place",dummyArray,@"data", nil], nil];

NSLog(@"demoArrayOfObjects = %@",demoArrayOfObjects);

Output:

demoArrayOfObjects = (
    {
    Place = SouthAfrica;
    data =         (
                    {
            score = 280;
            team = India;
            wickets = 5;
        },
                    {
            score = 279;
            team = SouthAfrica;
            wickets = 9;
        }
    );
    date = "17-03-2018";
    result = "Ind win by 5 wickets";
    }
)

Solution

  • This pseudo code might help you implement datasource in swift.

    func prepareMatchInfo () -> Array<Dictionary<String,Any>>{

        var arrayOfMatches : Array<Dictionary<String,Any>> = Array<Dictionary<String,String>>();
        
        var arrayOfScores : Array<Dictionary<String,String>> = Array<Dictionary<String,String>>();
        arrayOfScores.append(getTeamScore(teamName: "India", score: "280", wickets: "5"));
        arrayOfScores.append(getTeamScore(teamName: "South Africa", score: "279", wickets: "6"));
    
        arrayOfMatches.append(getMatchInfo(place: "South Africa", data: arrayOfScores, date: Date(), result: "India Won by 5 Wickets"));
        
        return arrayOfMatches;
    }
    
    func getMatchInfo (place:String, data:Array<Dictionary<String,String>>, date:Date, result:String) -> Dictionary<String, Any>{
        var dict : Dictionary<String, Any> = Dictionary();
        dict["Place"] = place;
        dict["Data"] = data;
        dict["Date"] = date;
        dict["Result"] = result;
        return dict;
    }
    
    func getTeamScore (teamName:String, score:String, wickets:String) -> Dictionary<String, String>{
        var dict : Dictionary<String, String> = Dictionary();
        dict["TeamName"] = teamName;
        dict["Score"] = score;
        dict["Wickets"] = wickets;
        return dict;
    }