Change value of dictionary within array in Swift 2 - swift

I'm trying to change a value of a dictionary that is within an array. I made a small prototype in PlayGround:
var arr = [NSDictionary]()
arr.append(["name":"blue","view":"<object id=\"6787\">","visible":"true","locked":"false"])
arr.append(["name":"yellow","view":"<object id=\"345\">","visible":"true","locked":"false"])
arr.append(["name":"green","view":"<object id=\"123\">","visible":"false","locked":"true"])
//test remove
arr.removeAtIndex(2)
arr.count
//test edit
let nameChange = arr[1]
nameChange.setValue("black", forKey: "name")
arr[1]
But an error occurred, and I can not solve:
Some can help me?

Because you created your dictionary as NSDictionary - the values can't change once they are set. But you still want to change them using setValue() and thats why you have the error. The fix is easy, change it to NSMutableDictionary. BUT. You shouldn't use Objective-C API, when you have Swift API. Thats why you should use Swift's Dictionary. How? e.g.
var arr = [[String:String]]()
arr.append(["name":"blue","view":"<object id=\"6787\">","visible":"true","locked":"false"])
arr.append(["name":"yellow","view":"<object id=\"345\">","visible":"true","locked":"false"])
arr.append(["name":"green","view":"<object id=\"123\">","visible":"false","locked":"true"])
//test remove
arr.removeAtIndex(2)
arr.count
//test edit
var nameChange = arr[1]
nameChange["name"] = "black"

Finally Got Some Code,
let DuplicateArray: NSArray = array
let DuplicateMutableArray: NSMutableArray = []
DuplicateMutableArray.addObjectsFromArray(DuplicateArray as [AnyObject])
var dic = (DuplicateMutableArray[0] as! [NSObject : AnyObject])
dic["is_married"] = "false"
DuplicateMutableArray[self.SelectedIndexPath] = dic
array = []
array = (DuplicateMutableArray.copy() as? NSArray)!
//Output Will Be Like
array = [
{
"name": "Kavin",
"Age": 25,
"is_married": "false"
},
{
"name": "Kumar",
"Age": 25,
"is_married": "false"
}
]

Related

Retrieve dictionary from dictionary swift

I am converting objective c code in swift.
I am getting data from server which has a dictionaries in a dictionaries.
i am getting key value string but cannot get dictionary.
example data:
data = {
caption = hello;
image = {
a = "https://www.google.com/1024x1024";
b = "https://www.google.com/640x640";
c = "https://www.google.com/480x480";
d = "https://www.google.com/";
};
};
i can get caption
let dataDict = (mainDict[data] as? Dictionary<String,AnyObject>)!
Obj.caption=String(dataDict["caption"]!) //getting hello
Obj.imageDictionary = (dataDict["image"] as? Dictionary<String,String>)! //getting 0 key value pairs
initialised imageDictionary as
var imageDictionary = Dictionary<String, String>()
please suggest how to get the image dictionary, I want this dictionary to store in imageDictionary object.
Any suggestions would be highly appreciated!
Thanks in advance!
Try this:
let data : [String : Any] = ["caption" : "hello",
"image" :["a" : "https://www.google.com/1024x1024",
"b" : "https://www.google.com/640x640",
"c" : "https://www.google.com/480x480",
"d" : "https://www.google.com/",
]
]
let caption = data["caption"] as! String
let imageDictionary = data["image"] as! [String : String]
In imageDictionary, I am getting:
["b": "https://www.google.com/640x640", "a": "https://www.google.com/1024x1024", "d": "https://www.google.com/", "c": "https://www.google.com/480x480"]
Screenshot:

How do I add more items to this type of name value pair array? [duplicate]

I have a simple Dictionary which is defined like:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
Now I want to add an element into this dictionary: 3 : "efg"
How can I append 3 : "efg" into this existing dictionary?
You're using NSDictionary. Unless you explicitly need it to be that type for some reason, I recommend using a Swift dictionary.
You can pass a Swift dictionary to any function expecting NSDictionary without any extra work, because Dictionary<> and NSDictionary seamlessly bridge to each other. The advantage of the native Swift way is that the dictionary uses generic types, so if you define it with Int as the key and String as the value, you cannot mistakenly use keys and values of different types. (The compiler checks the types on your behalf.)
Based on what I see in your code, your dictionary uses Int as the key and String as the value. To create an instance and add an item at a later time you can use this code:
var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"
If you later need to assign it to a variable of NSDictionary type, just do an explicit cast:
let nsDict = dict as! NSDictionary
And, as mentioned earlier, if you want to pass it to a function expecting NSDictionary, pass it as-is without any cast or conversion.
you can add using the following way and change Dictionary to NSMutableDictionary
dict["key"] = "value"
I know this might be coming very late, but it may prove useful to someone.
So for appending key value pairs to dictionaries in swift, you can use updateValue(value: , forKey: ) method as follows :
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
SWIFT 3 - XCODE 8.1
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
So, your dictionary contains:
dictionary[1: Hola, 2: Hello, 3: Aloha]
If your dictionary is Int to String you can do simply:
dict[3] = "efg"
If you mean adding elements to the value of the dictionary a possible solution:
var dict = Dictionary<String, Array<Int>>()
dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
Swift 3+
Example to assign new values to Dictionary. You need to declare it as NSMutableDictionary:
var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
For whoever reading this for swift 5.1+
// 1. Using updateValue to update the given key or add new if doesn't exist
var dictionary = [Int:String]()
dictionary.updateValue("egf", forKey: 3)
// 2. Using a dictionary[key]
var dictionary = [Int:String]()
dictionary[key] = "value"
// 3. Using subscript and mutating append for the value
var dictionary = [Int:[String]]()
dictionary[key, default: ["val"]].append("value")
In Swift, if you are using NSDictionary, you can use setValue:
dict.setValue("value", forKey: "key")
Given two dictionaries as below:
var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]
Here is how you can add all the items from dic2 to dic1:
dic2.forEach {
dic1[$0.key] = $0.value
}
Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.
Example-
var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")
Result-
▿ : 2 elements
- key : "userId"
- value : 866
▿ : 2 elements
- key : "otherNotes"
- value : "Hello"
[String:Any]
For the fellows using [String:Any] instead of Dictionary below is the extension
extension Dictionary where Key == String, Value == Any {
mutating func append(anotherDict:[String:Any]) {
for (key, value) in anotherDict {
self.updateValue(value, forKey: key)
}
}
}
As of Swift 5, the following code collection works.
// main dict to start with
var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]
// dict(s) to be added to main dict
let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
let myDictUpdated : Dictionary = [ 5 : "lmn"]
let myDictToBeMapped : Dictionary = [ 6 : "opq"]
myDict[3]="fgh"
myDict.updateValue("ijk", forKey: 4)
myDict.merge(myDictToMergeWith){(current, _) in current}
print(myDict)
myDict.merge(myDictUpdated){(_, new) in new}
print(myDict)
myDictToBeMapped.map {
myDict[$0.0] = $0.1
}
print(myDict)
To add new elements just set:
listParameters["your parameter"] = value
There is no function to append the data in dictionary. You just assign the value against new key in existing dictionary. it will automatically add value to the dictionary.
var param = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)
The output will be like
["Name":"Aloha","user" : "Aloha 2","questions" : ""Are you mine"?"]
To append a new key-value pair to a dictionary you simply have to set the value for the key. for eg.
// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]
// Add a new key with a value
dict["email"] = "john.doe#email.com"
print(dict)
Output -> ["surname": "Doe", "name": "John", "email": "john.doe#email.com"]
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample#email.com"
print(dict)
Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:
newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }
#Dharmesh In your case, it will be,
newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }
Please let me know if you find any issues in using above syntax.
Swift 5 happy coding
var tempDicData = NSMutableDictionary()
for temp in answerList {
tempDicData.setValue("your value", forKey: "your key")
}
I added Dictionary extension
extension Dictionary {
func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
var result = self
dict.forEach { key, value in result[key] = value }
return result
}
}
you can use cloneWith like this
newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }
if you want to modify or update NSDictionary then
first of all typecast it as NSMutableDictionary
let newdictionary = NSDictionary as NSMutableDictionary
then simply use
newdictionary.setValue(value: AnyObject?, forKey: String)

Swift: NSArray to Set?

I am trying to convert an NSArray to a Swift Set.
Not having much luck.
What is the proper way to do so?
For example if I have an NSArray of numbers:
#[1,2,3,4,5,6,7,8]
How do I create a Swift Set from that NSArray?
If you know for sure that the NSArray contains only number objects
then you can convert it to an Swift array of Int (or Double or
NSNumber, depending on your needs) and create a set from that:
let nsArray = NSArray(array: [1,2,3,4,5,6,7,8])
let set = Set(nsArray as! [Int])
If that is not guaranteed, use an optional cast:
if let set = (nsArray as? [Int]).map(Set.init) {
print(set)
} else {
// not an array of numbers
}
Another variant (motivated by #JAL's comments):
let set = Set(nsArray.flatMap { $0 as? Int })
// Swift 4.1 and later:
let set = Set(nsArray.compactMap { $0 as? Int })
This gives a set of all NSArray elements which are convertible
to Int, and silently ignores all other elements.
import Foundation
let nsarr: NSArray = NSArray(array: [1,2,3,4,5])
var set: Set<Int>
guard let arr = nsarr as? Array<Int> else {
exit(-1)
}
set = Set(arr)
print(set.dynamicType)
dump(set)
/*
Set<Int>
▿ 5 members
- [0]: 5
- [1]: 2
- [2]: 3
- [3]: 1
- [4]: 4
*/
with help of free bridging, it should be easy ...
If you know you're working with Ints, you could always iterate through your array and manually add each element to a Set<Int>:
let theArray = NSArray(array: [1,2,3,4,5,6,7,8])
var theSet = Set<Int>()
for number in (theArray as? [Int])! {
theSet.insert(number)
}
print(theSet) // "[2, 4, 5, 6, 7, 3, 1, 8]\n"
I'm trying to work out a more elegant solution with map, I'll update this answer as I make more progress.
Thanks to MartinR's suggestion to use unionInPlace (which takes in the SequenceType returned from map) instead of insert on the Set, this can be accomplished like so:
let theArray = NSArray(array: [1,2,3,4,5,6,7,8])
var mySet = Set<Int>()
mySet.unionInPlace(theArray.map { $0 as! Int })
Note that this may not be the safest solution due to the explicit cast to Int.
var array = [1,2,3,4,5]
var set = Set(array)

How to remove duplicated objects from NSArray?

I have NSArray() which is include names but there's duplicated names how can i remove them ?
After parse query adding the objects to the NSArray and its duplicated
var names = NSArray()
let query = PFQuery(className: "test")
query.whereKey("receivers", equalTo: PFUser.currentUser()!.username!)
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
if error == nil {
self.names = objects!
let set = NSSet(array: self.names as [AnyObject])
print(objects!.count)
// count is 4
// database looks like this (justin , kevin , kevin , joe)
If your names are strings you could create NSSet from array and it will have only different names.
let names = ["John", "Marry", "Bill", "John"]
println(names)
let set = NSSet(array: names)
println(set.allObjects)
prints:
"[John, Marry, Bill, John]"
"[Bill, John, Marry]"
Update #1
With new information in question (code fragment) it may look like this
var set = Set<String>()
for test in objects as [Test] {
set.insert(test.sender)
}
self.names = Array(set)
To expand on John's answer, an NSSet will, by definition, only contain a single copy of each object that hashes to be equal. So, a common pattern is to convert the array to a set and back.
This will work for any object type that has a reasonable implementation of -hash and -isEqual:. As John shows, String is one such object.
You could also do it with pure Swift:
let arrayWithDuplicates = [ "x", "y", "x", "x" ]
let arrayWithUniques = Array(Set(arrayWithDuplicates)) // => [ "y", "x" ]
But, it looks like you're already working with NSArray, so I think the John's example is more applicable.
Also, as my example shows, be aware that the order of the final array is not guaranteed to be in the same order as your original. If you want that, I think you can use NSOrderedSet instead of NSSet.
Here is a more complicated way to approach this that works. You could just run through a loop of the array and create a new one from the original. For example:
var check = 0
let originalArray:NSMutableArray = ["x", "y", "x", "z", "y", "z"]
let newArray: NSMutableArray = []
println(originalArray)
for var int = 0; int<originalArray.count; ++int{
let itemToBeAdded: AnyObject = originalArray.objectAtIndex(int)
for var int = 0; int<newArray.count; ++int{
if (newArray == ""){
break;
}
else if ((newArray.objectAtIndex(int) as! String) != itemToBeAdded as! String){
}
else if ((newArray.objectAtIndex(int) as! String) == itemToBeAdded as! String){
check = 1
break
}
}
if (check == 0){
newArray.addObject(itemToBeAdded)
}
}
Basically I set a check var = 0. for every object in the originalArray, it loops through the newArray to see if it already exists and if it does the check var gets set to 1 and the object does not get added twice.

Swift: changing value inside class structured array

class Store: NSObject {
var storeNumber : NSString!
var storetitle : NSString!
init(number:NSString, stTitle title : NSString) {
self.storeNumber = number
self.storetitle = title
}
}
var arrStore : NSMutableArray! = NSMutableArray()
var store = Store(number: "1", stTitle: "Adidas")
self.arrStore.addObject(store)
var store = Store(number: "2", stTitle: "Nike")
self.arrStore.addObject(store)
I want to change the value of the title "Nike"? How could I do that?
The below code changes the title of all objects in arrStore array:
self.arrStore.setValue("rebook", forKey: "storetitle")
I want something like:
self.arrStore.setValue("rebook", forKey: "storetitle")[1]
But unfortunately it is wrong!
Thank you in advance.
Just use:
let store = arrStore.objectAtIndex(1) as Store
store.storetitle = "New title"
or the more concise syntax:
let store = arrStore[1] as Store
store.storetitle = "New title"
I would suggest you to use Swift array rather than NSMutableArray.
var array = [Store]()
var store = Store(number: "1", stTitle: "Adidas")
self.arrStore.append(store)
var store = Store(number: "2", stTitle: "Nike")
self.arrStore.append(store)
array[0].storetitle = "New Title"