1
for tempExportData in exportDataArray {
    let tmpRegNO:NSString = (tempExportData as AnyObject).object(forKey: kRegisteredNo) as! NSString
    print("tmpRegNO is",tmpRegNO)
    var tmpNoArray:Array = [String]()
    tmpNoArray.append(tmpRegNO as String)
    print("Count is",tmpNoArray.count)
    print("ARRAY is",tmpNoArray)
}

I am trying to add string value i.e tmpRegNO to the Array tmpNoArray.
In this I can able to add only one value to the array at a time.
How to add the next value to that array when it is looping for second time.

4
  • you need to initialize the array outside the for in loop Commented Dec 16, 2017 at 12:42
  • @ReinierMelian thank you so much for your quickest response... Commented Dec 16, 2017 at 12:50
  • your welcome, please accept my answer if solves your issue Commented Dec 16, 2017 at 12:51
  • I did not notice that small issue,, thank you all Commented Dec 16, 2017 at 12:51

2 Answers 2

1

As already mentioned you have to declare the array before entering the loop.

Your code is very objectivecish. This is a swiftier version. Don't annotate types the compiler can infer and use key subscription rather than ugly casting to AnyObject and objectForKey:.

var tmpNoArray = [String]()

for tempExportData in exportDataArray {
    let tmpRegNO = tempExportData[kRegisteredNo] as! String
    print("tmpRegNO is",tmpRegNO)

    tmpNoArray.append(tmpRegNO)

    print("Count is",tmpNoArray.count)
    print("ARRAY is",tmpNoArray)
}

You can even write the whole expression in one line:

let tmpNoArray = exportDataArray.flatMap { $0[kRegisteredNo] as? String }
Sign up to request clarification or add additional context in comments.

Comments

0

You need move the tempNoArray initialization outside of your for in loop, if not the your array will be initialized once for every item in your exportDataArray remaining only the las item as consequence

You need something like this

var tmpNoArray:Array = [String]()
for tempExportData in exportDataArray{

        if let tmpRegNO = tempExportData[kRegisteredNo] as? String   
        {

        print("tmpRegNO is",tmpRegNO)
        tmpNoArray.append(tmpRegNO as String)

        print("Count is",tmpNoArray.count)
        print("ARRAY is",tmpNoArray)
        }
    }

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.