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

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)

Related

Array to Array copy

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

Swift 3: how to sort Dictionary's key and value of struct

This is my Struct,by Swift 3. I know the Dictionary is not stored sequence like an Array and that is my problem. I want to get my Dictionary sequence as I set in ViewArray. I can get the ctC Dictionary, but how can i sort the keys or values as i set in ViewArrayplease and appreciate the help.
struct CTArray {
var ctname: String
var ctkey: String
var ctC: [String:String]
}
var ViewArray:[CTArray] = []
ViewArray += [CTArray(ctname: "kerish", ctkey: "KH", ctC: ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"])]
ViewArray += [CTArray(ctname: "tainers", ctkey: "TNN", ctC: ["letGor":"one", "washi":"testing", "monk":"lasth"])]
ViewArray += [CTArray(ctname: "techiu", ctkey: "TCU", ctC: ["22":"tt", "wke":"303", "lenth":"highest"])]
i want to show them in my TableView Cell sorted like these:
the ViewArray[0].ctC.key sorted like [mon, kis, Bat, orlno]
the ViewArray[1].ctC.key sorted like [letGor, washi, monk]
the ViewArray[2].ctC.value sorted like [tt, 303, highest]
It is not clear to me what you are asking, but I'll offer this in case it helps.
I know the Dictionary is not stored sequence like an Array and that is my problem.
If you want to access a dictionary by a certain order of its keys then you can create an array of just the keys in the order you required and use that to access the dictionary. An example is probably easier to follow:
Starting with one of your dictionaries:
let dict = ["mon":"Apple", "kis":"aone", "Bat":"Best", "orlno":"bOne"]
print(dict)
this output:
["Bat": "Best", "kis": "aone", "orlno": "bOne", "mon": "Apple"]
which is not what you want. Now introduce a key array and use that to access the dictionary:
let keyOrder = ["mon", "kis", "Bat", "orlno"]
for key in keyOrder
{
print("\(key): \(dict[key]!)")
}
this outputs:
mon: Apple
kis: aone
Bat: Best
orlno: bOne
which is the order you wish.
The same idea can be used anywhere you want to use/show/etc. the keys in a particular order, by using the keyOrder array as part of dictionary access you are making it appear as though the dictionary entries are "stored in sequence" as you put it.
HTH
var object1 = viewArray[0].ctC.flatMap({$0.key})
var object2 = viewArray[1].ctC.flatMap({$0.key})
var object3 = viewArray[2].ctC.flatMap({$0.value})
print(object1)
print(object2)
print(object3)
Outputs:
["Bat", "kis", "orlno", "mon"]
["letGor", "monk", "washi"]
["highest", "tt", "303"]

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

Swift: how to make array of mutable dictionaries? [duplicate]

I’m new to Swift and have been having some troubles figuring out some aspects of Arrays and Dictionaries.
I have an array of dictionaries, for which I have used Type Aliases - e.g.
typealias myDicts = Dictionary<String, Double>
var myArray : [myDicts] = [
["id":0,
"lat”:55.555555,
"lng”:-55.555555,
"distance":0],
["id":1,
"lat": 44.444444,
"lng”:-44.444444,
"distance":0]
]
I then want to iterate through the dictionaries in the array and change the “distance” key value. I did it like this:
for dict:myDicts in myArray {
dict["distance"] = 5
}
Or even specifically making sure 5 is a double with many different approaches including e.g.
for dict:myDicts in myArray {
let numberFive : Double = 5
dict["distance"] = numberFive
}
All my attempts cause an error:
#lvalue $T5' is not identical to '(String, Double)
It seems to be acting as if the Dictionaries inside were immutable “let” rather than “var”. So I randomly tried this:
for (var dict:myDicts) in myArray {
dict["distance"] = 5
}
This removes the error and the key is indeed assigned 5 within the for loop, but this doesn't seem to actually modify the array itself in the long run. What am I doing wrong?
The implicitly declared variable in a for-in loop in Swift is constant by default (let), that's why you can't modify it directly in the loop.
The for-in documentation has this:
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
In the example above, index is a constant whose value is automatically
set at the start of each iteration of the loop. As such, it does not
have to be declared before it is used. It is implicitly declared
simply by its inclusion in the loop declaration, without the need for
a let declaration keyword.
As you've discovered, you can make it a variable by explicitly declaring it with var. However, in this case, you're trying to modify a dictionary which is a struct and, therefore, a value type and it is copied on assignment. When you do dict["distance"] = 5 you're actually modifying a copy of the dictionary and not the original stored in the array.
You can still modify the dictionary in the array, you just have to do it directly by looping over the array by index:
for index in 0..<myArray.count {
myArray[index]["distance"] = 5
}
This way, you're sure to by modifying the original dictionary instead of a copy of it.
That being said, #matt's suggestion to use a custom class is usually the best route to take.
You're not doing anything wrong. That's how Swift works. You have two options:
Use NSMutableDictionary rather than a Swift dictionary.
Use a custom class instead of a dictionary. In a way this is a better solution anyway because it's what you should have been doing all along in a situation where all the dictionaries have the same structure.
The "custom class" I'm talking about would be a mere "value class", a bundle of properties. This was kind of a pain to make in Objective-C, but in Swift it's trivial, so I now do this a lot. The thing is that you can stick the class definition for your custom class anywhere; it doesn't need a file of its own, and of course in Swift you don't have the interface/implementation foo to grapple with, let alone memory management and other stuff. So this is just a few lines of code that you can stick right in with the code you've already got.
Here's an example from my own code:
class Model {
var task : NSURLSessionTask!
var im : UIImage!
var text : String!
var picurl : String!
}
We then have an array of Model and away we go.
So, in your example:
class MyDict : NSObject {
var id = 0.0
var lat = 0.0
var lng = 0.0
var distance = 0.0
}
var myArray = [MyDict]()
let d1 = MyDict()
d1.id = 0
d1.lat = 55.55
d1.lng = -55.55
d1.distance = 0
let d2 = MyDict()
d2.id = 0
d2.lat = 44.44
d2.lng = -44.44
d2.distance = 0
myArray = [d1,d2]
// now we come to the actual heart of the matter
for d in myArray {
d.distance = 5
}
println(myArray[0].distance) // it worked
println(myArray[1].distance) // it worked
Yes, the dictionary retrieved in the loop is immutable, hence you cannot change.
I'm afraid your last attempt just creates a mutable copy of it.
One possible workaround is to use NSMutableDictionary:
typealias myDicts = NSMutableDictionary
Have a class wrapper for the Swift dictionary or array.
class MyDictionary: NSObject {
var data : Dictionary<String,Any>!
init(_ data: Dictionary<String,Any>) {
self.data = data
}}
MyDictionary.data

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