1

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?

5
  • Why is this question tagged obj-c and obj-c++? Commented Jul 8, 2016 at 13:26
  • in swift you have initialize your variables or mark them as optional Commented Jul 8, 2016 at 13:26
  • @angger have you try my ans? Commented Jul 8, 2016 at 13:29
  • @Vvk i just try to explain swift variable declaration logic instead of direct answer it. Commented Jul 8, 2016 at 13:34
  • @AliKıran Thanks for explaination :) Commented Jul 8, 2016 at 13:36

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you ! I guess I'm being reckless there
@Angger welcome. There are many ways to initialize array but this one is simple.
2

change:

var Person : [String:String]

to:

var Person = [String:String]()

to initialise the array before using it.

Comments

1

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]]];
   }
 }

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.