add multiple objects to swift array in for loop - arrays

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.

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 }

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)
}
}

Related

How to store multiple datas in an Array in swift 4?

I am getting a JSON from an API. So, I want to store a particular value with key SKU. So, what I did was:
var skuArr = [""]
{ (response, error) in
if (error != nil)
{
print("Error \(error.debugDescription)")
}
else
{
self.coinsArr = response.arrayObject as? Array<Dictionary<String, Any>>
for i in 0 ..< (self.coinsArr?.count)!
{
self.skuArr = [response[i]["sku"].rawValue as! String]
}
}
So, with this I am getting the array in skuArr, but when i is 0 I am getting ["a"], and when i is 1 I want it to be ["a","b"], but it gives ["b"] only and when the loop ends with only the last value and not with ["a","b","c","d"] which I want as the final result. How can I insert each of them in the Array?
First of all declare skuArr as empty string array.
var skuArr = [String]()
And this is Swift. There are better ways than ugly index based loops to extract data for example with map or compactMap
if let result = response.arrayObject as? Array<Dictionary<String, Any>> {
self.coinsArr = result
self.skuArr = result.compactMap{ $0["sku"] as? String }
}
And why is coinsArr declared as optional as you are going to force unwrap it anyway? It's highly recommended to use non-optional types as much as possible. Non-optionals can never cause a well-liked unexpected found nil crash
Don't use this:
self.skuArr = [response[i]["sku"].rawValue as! String]
As this will replace the previous value with new one.
Use .append to insert into array.
self.skuArr.append([response[i]["sku"].rawValue as! String])
EDIT
change your initialisation as below:
skuArr: [String] = []

How to cast a dictionary [String:Bool] to an array [String] in swift?

I'm trying to cast a dictionary of [String:Bool] to an array of string.
my code is:
var action = [Nourishing:true, Radiance:true]
let actionArray = [action.keys.description] as? [String]
but the result comes out as:
["[\"Nourishing\", \"Radiance\"]"]
How do I fix this?
You should use this directly
let actionArray = Array(action.keys)

Swift: array check for object at index

I have an data model object with several properties. I have a dynamic array that will sometimes have some but not all of the object properties inside of it.
How do I safely check if the array as anything at it's index
DataModel
class Order{
var item0:String?
var item1:String?
var item2:String?
}
Array:
var myArray = [String]()
The guard statements are where I'm having issues checking to see if there are elements inside the array at different indexes.
Btw the array will never have more then 3 elements inside of it.
let order = Order()
order.item0 = "hat"
order.item1 = "sneakers"
myArray.append(order.item0)
myArray.append(order.item1)
//sometimes there may or may not be item2
let placedOrder = Order
//These guard statements aren't working
guard case let placedOrder.item0 = myArray[0] else {return}
guard case let placedOrder.item1 = myArray[1] else {return}
//There isn't anything at myArray[2] but I need to safely check anyway
guard case let placedOrder.item2 = myArray[2] else {return}
1st The array should hold the data model type and not it's properties:
var orders = [Order]()
//changed the array's name from myArray to orders instead
2nd Add the data model object to the array:
let orderOne = Order()
orders.append(orderOne)
3rd loop through the array, check that the element's properties aren't nil:
for order in orders{
if order.item0 != nil{
//do something with order.item0
}
if order.item1 != nil{
//do something with order.item1
}
if order.item2 != nil{
//do something with order.item2
}
}

Swift: Accessing array value in array of dictionaries

I am currently struggling with obtaining a value from an array inside an array of dictionaries. Basically I want to grab the first "[0]" from an array stored inside an array of dictionaries. This is basically what I have:
var array = [[String:Any]]()
var hobbies:[String] = []
var dict = [String:Any]()
viewDidLoad Code:
dict["Name"] = "Andreas"
hobbies.append("Football", "Programming")
dict["Hobbies"] = hobbies
array.append(dict)
/// - However, I can only display the name, with the following code:
var name = array[0]["Name"] as! String
But I want to be able to display the first value in the array stored with the name, as well. How is this possible?
And yes; I know there's other options for this approach, but these values are coming from Firebase (child paths) - but I just need to find a way to display the array inside the array of dictionaries.
Thanks in advance.
If you know "Hobbies" is a valid key and its dictionary value is an array of String, then you can directly access the first item in that array with:
let hobby = (array[0]["Hobbies"] as! [String])[0]
but this will crash if "Hobbies" isn't a valid key or if the value isn't [String].
A safer way to access the array would be:
if let hobbies = array[0]["Hobbies"] as? [String] {
print(hobbies[0])
}
If you use a model class/struct things get easier
Given this model struct
struct Person {
let name: String
var hobbies: [String]
}
And this dictionary
var persons = [String:Person]()
This is how you put a person into the dictionary
let andreas = Person(name: "Andreas", hobbies: ["Football", "Programming"])
persons[andreas.name] = Andreas
And this is how you do retrieve it
let aPerson = persons["Andreas"]

Cannot assign value of type String:NSObject to type String:NSObject

I have a dictionary/array, looks like this:
var myArray: [[String:NSObject]] = []
let newItem = [
[
"caseNumber" : caseToAdd,
"formType" : formType,
"caseStatus" : caseStatus,
"caseDetails" : caseDetails,
"caseLUD" : caseLUD,
"friendlyName" : ""
]]
//Add new item to existing array
myArray += newItem
This works fine, I can access the items etc. But now I want to save it to NSUserDefaults so I can access it again in the future. I can save it just fine, but trying to load it again is giving me an issue:
myArray = HelperSavedData().loadMyCasesFromNSUserDefaults
Here is the HelperSavedData class:
public class HelperSavedData {
let defaults = NSUserDefaults.standardUserDefaults()
public func saveMyCasesToNSUserDefaults(input:NSObject){
defaults.setObject(input, forKey: "myArray")
defaults.synchronize()
}
public func loadMyCasesFromNSUserDefaults() -> [[String:NSObject]]? {
if let savedArray = defaults.valueForKey("myArray") {
return ((savedArray) as! [[String : NSObject]])
}
return nil
}
}
But I am getting the error:
Cannot assign value of type () -> [[String: NSObject]]? to type [[String: NSObject]]
You can't assign an optional type to a non-optional type without some amount of unwrapping.
You've defined myArray as being a non-optional array of dictionaries.
var myArray: [[String:NSObject]] = []
The variable, myArray can never be nil.
You've defined loadMyCasesFromNSUserDefaults() as returning an optional array of dictionaries.
public func loadMyCasesFromNSUserDefaults() -> [[String:NSObject]]?
That is to say, this method could return nil.
So we have to decide what makes most sense in terms of how to handle our variables. Does it make sense to allow nil to be assign into our myArray variable? If so, make it an optional as other answers suggest:
var myArray: [[String:NSObject]]?
But maybe it never makes sense for myArray to be nil. In this case, don't change the declaration of myArray. Instead, determine how we handle the case in which your method returns nil.
We could say... we only want to assign into myArray if we load a non-nil array from the method:
var myArray = [[String:NSObject]]()
if let loadedArray = loadMyCasesFromNSUserDefaults() {
myArray = loadedArray
}
myArray += newItem
Or we could use the Nil-Coalescing operator and assign a default value into myArray if loadMyCasesFromNSUserDefaults() returns nil.
var myArray = loadMyCasesFromNSUserDefaults() ?? [newItem]
And there are plenty of other ways to deal with nil and optionals as well.
What is key here, is we need to make a few decisions.
Should myArray ever allowed to be nil? Does that make sense?
If myArray shouldn't be nil, what makes sense for handling the case in which our method returns nil? How do we want to handle that?
You're returning an optional value from loadMyCasesFromNSUserDefaults() and trying to save it in a non-optional value. Try changing the myArray declaration like this
var myArray: [[String:NSObject]]?
loadMyCasesFromNSUserDefaults() return [[String:NSObject]]? which is an optional value ,pls try var myArray?: [[String:NSObject]] = []

Resources