Reputation: 805
I want to add value to an empty array by looping another array's value
var Person : [String:String]
var data : [String:String] = [
"name" : "John",
"age" : "22"
]
for (index, value) in data {
Person[index] = value
}
And I got this error "variable Person passed by reference before being initialized"
Why is that?
Upvotes: 1
Views: 539
Reputation: 685
What you are declaring here is a dictionary, not an array. The same result that is being achieved by the above code (in the answer from Vvk) could be achieved by simply writing:
var Person = [ "name" : "John", "age" : "22" ]
If you want to use a loop to add items to a dictionary then you could, but I don't see the value of it in this context.
If the aim is to set values in Person
equal to the values in data
then you can just write:
var Person = [String:String]()
var data = [ "name" : "John", "age" : "22" ]
Person = data
No need for a loop, unless the wider scope of your project requires it.
Upvotes: 1
Reputation: 4043
Try This
// Array initialization
var Person = [String:String]()
var data : [String:String] = [
"name" : "John",
"age" : "22"
]
for (index, value) in data {
Person[index] = value
}
Hope it helps you.
Upvotes: 3
Reputation: 9599
In Objective C
#import "ViewController.h"
@interface ViewController ()
{
NSMutableArray *arr,*arrSecond;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//First Array
arr = [[NSMutableArray alloc]initWithObjects:@"iOS",@"Android",@"Windows",@"Blackberry",@"Symbion",@"Bada",nil];
arrSecond = [[NSMutableArray alloc]init];
for(int i=0;i<[arr count];i++)
{
//Second Array inside the for loop.It is getting objects from First loop of for
[arrSecond addObject:[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]]];
}
}
Upvotes: 1
Reputation: 21137
change:
var Person : [String:String]
to:
var Person = [String:String]()
to initialise the array before using it.
Upvotes: 2