Array to Array copy - ios

I have two arrays. One is:
var array = [[String]]()
The second one is:
var finalArray = NSMutableArray()
array is blank.
I want to copy all the data from the final array to array.
For these two different types of array, direct this code won't work.
array = finalArray

An NSArray can be converted to a Swift array of a given element type with the as? operator, like so:
array = finalArray as? [[String]] ?? []
Note that we have to use the conditional typecast operator as? because it's not known at compile-time whether finalArray actually is an array of string arrays (since NSArray does not use generics in Swift).

Related

Casting Syntax to Loop Through Array of Arrays in Swift

I have an NSArray consisting of NSArrays of strings created in Objective-C.
I now want to loop through the items in the array in a swift class and am having trouble with the syntax.
The original Objective-C Array of arrays looks like the following:
NSArray* shapes =#[#[#"square",#"square.png"],#[#"circle",#"circle.png"],#[#"square",#"square.png"]];
I am able to get and print the Array from the Objective-C class using:
let shapes:Array = Utilities.sharedInstance().getShapes
The following to loop through the array, however, is not compiling:
var term : String = ""
var pic : String = ""
for shape in shapes {
term = shape[1] //ERROR HERE
pic = shape[2] //SAME ERROR HERE
}
It gives the error: Type 'Any' has no subscript members
What is the proper syntax to loop through the elements?
You can try
let shapes = Utilities.sharedInstance().getShapes as! [[String]]
Your Array elements are of type Any so you can't use [] with them until you cast , it's always the case when you use bridged code from objective-c , so you have to be specific about the actual type you use , also i encourage
struct Item {
let term,pic:String
}
Then
let res:[Item] = shapes.map { Item(term:$0[0],pic:$0[1]) }
an irrelevant note but important you can do
NSArray* shapes = #[#"square",#"circle",#"square"];
then the matter of appending .png is simple instead of having an [[String]] directly it's [String]

I have and array inside the value of dictionary

I have an dictionary and the value containts the array of string as follows
arr = ["key":"["a","b","c","d","e","f","g"]"]
I want the new array to be like
let array = ["a","b","c","d","e","f","g"]
How to parse it
You can access dictionary items in few different ways, the easiest is:
let array = arr["key"]
You may need to conditionally unwrap it
if let array = arr["key"] as? [String] {
// rest of code with array
}

Swift: How to Create Array Holding Dictionaries

I'm teaching myself swift and am trying to create an array holding dictionaries. The dictionaries are in the following format: String: Any (usually Strings, but sometimes additional arrays of dictionaries).
Is this the correct way to create an array capable of holding dictionaries?
var contentArray: [Dictionary<String, Any>] = []
I went through the question history and saw your edit. indexOfObjectPassingTest is a method on NSArray. You are asking about Array which is a different (though related) type.
Here's how to declare the array:
var contentArray = [[String: Any]]()
Here's how to get the index of an item:
let index1 = contentArray.index(of: aDict)
let index2 = contentArray.index(where: { (some conditions) })

What is the difference between append and addObject + Compare two date

I am little bit confuse about, what is the difference between append and addObject.
I am using both in my code but confuse what is the difference between them.
addObject
self.dateArrayServer.addObject(date as! String)
append
dateArrayCalendar.append(dateFormatatter.stringFromDate(dateStart))
And Second problem is
Hi,
I am try to compare two date-
dateArrayForCompare, is the date which i get from NSDate and, dateArrayServer, is the date which i get from json response.
var dateArrayServer = NSMutableArray()
var dateArrayCalendar = NSMutableArray()
var dateArrayForCompare = NSMutableArray()
let dateHomework:NSArray = allAsign.valueForKey("date") as! NSArray
let homeWork = allAsign.valueForKey("assignmenttype") as! NSArray
for date in dateHomework{
self.dateArrayServer.addObject(date as! String)
}
let sys_date = NSDate()
print("System Date: \(sys_date)")
let df = NSDateFormatter()
df.dateFormat = "dd-MM-yyyy"
let currentDate = df.stringFromDate(sys_date)
print("String Date: \(currentDate)")
for dt in 0...self.dateArrayServer.count-1
{
if(self.dateArrayServer.objectAtIndex(dt) .isEqualToString("\(self.dateArrayForCompare)"))
{
print("Assignment on date: \(self.dateArrayServer.objectAtIndex(dt)) are:\n\(allAsign.objectAtIndex(dt))")
}else
{
print("\(self.dateArrayServer.objectAtIndex(dt)) doesn't match with \(self.dateArrayForCompare) ")
}
}
But get this result-
not a major different but i think i can explain it.
in swift two data type declare first "let" and "var" this two type accept all type of data .
but whenever you add array in "var" but not declare this is NSArray or NSMutableArray then you put any object on last position in it then you use append.
appen is like "+=" operator so it add that value on last position
var Array = ["1","2"]
Array.append(["3"])
//Result :- "1","2","3"
But you Declare as
NSMutableArray or NSArray
then you must use addObject like
var Array = NSMutableArray()
Array.addObject("1")
Array.addObject("2")
Array.addObject("3")
//Result :- "1","2","3"
And other different
append is get that value and put on last index .
addObject is get that Object and put on last index
and value and object have different meaning.
Add(anObject: Any) on a NSMutableArray is equal to Append(element: Element) on an array,
Append in documentation:
Adds a new element at the end of the array.
Use this method to append a single element to the end of a mutable array.
var numbers = [1, 2, 3, 4, 5]
numbers.append(100)
print(numbers)
// Prints "[1, 2, 3, 4, 5, 100]"
Because arrays increase their allocated capacity using an exponential
strategy, appending a single element to an array is an O(1) operation
when averaged over many calls to the `append(_:)` method. When an array
has additional capacity and is not sharing its storage with another
instance, appending an element is O(1). When an array needs to
reallocate storage before appending or its storage is shared with
another copy, appending is O(*n*), where *n* is the length of the array.
- Parameter newElement: The element to append to the array.
- Complexity: Amortized O(1) over many additions. If the array uses a
bridged `NSArray` instance as its storage, the efficiency is
unspecified.
Add object in documentation:
The object to add to the end of the array’s content. This value must not be nil.
Difference between append and addObject
Append : It appends your array with multiple items like for exa
var cityArray: String[] = ["Portland","San Francisco","Cupertino","Seattle"]
cityArray.append(["Vancouver", "Los Angeles", "Eugene"])
In append you can add multiple elements at a time
there is a property appendContentsof("collectiontype or sequencetype element") with it you can add multiple elements
AddObject : It add one object at a time at the end of array
but notice that NSArray and NSMutableArray doesn't have property append keyword, So you can not use append in this type of array
Mainly difference between append and addobject with example.
You already know the difference between NSArray and NSMutableArray. NSArray its a fixed array and NSMutablearray is the dynamic Array means you can increase the size of this Array in Run time so its depend on your requirement which one is the best. Because if you are using the NSArray means you don't have required to increase the value in run time then you can use NSArray with append and in Run time You want to increase the value then you can use NSMutablearray and addobject:.
NSArray when you are using the Array then you can use append object like this.
var str1:String = "John"
var str2:String = "Bob"
var myArray = ["Steve", "Bill", "Linus", "Bret"]
myArray.append(str1)
myArray.append(str2)
NSMutableArray when you are using the NSMutableArray then you can use addobject
var myArray1 : NSMutableArray = ["Hello"]
myArray1.addObject(str1)

Create an array in swift

I'm searching really much, but maybe I can't understand the results.
I found only that a array in SWIFT have as index int-values
var myArray = [String]()
myArray.append("bla")
myArray.append("blub")
println(myArray[0]) // -> print the result bla
But I will add a String with an String as index-key
var myArray = [String:String]()
myArray.append("Comment1":"bla")
myArray.append("Comment2":"blub")
println(myArray["Comment1"]) // -> should print the result bla
How should i declare the array and how I can append a value then to this array?
Your second example is dictionary
myArray["key"] = "value"
If you want array of dictionaries you would have to declare it like this
var myArray: [[String: String]]
Your first example is an array. Your second example is a dictionary.
For a dictionary you use key value pairing...
myArray["Comment1"] = "Blah"
You use the same to fetch values...
let value = myArray["Comment1"]
println(value)
You got the concept of array in the first example but for the second one you need a dictionary as they operate on key value pair
// the first String denotes the key while the other denotes the value
var myDictionary :[String:String] = ["username":"NSDumb"]
let value = myDictionary["username"]!;
println(value)
Quick reference for dictionaries collection type can be found here

Resources