I need to know that how can i make a copy of NSDictionary to NSMutableDictionary and change values of there.
Edit
I ned to know how to modify data of a NSDictionary. I got to know that
Copy data of NSDictionary to a NSMutableDictionary. and then modify data in NSMutableDictionary
let f : NSDictionary = NSDictionary()
var g = f.mutableCopy()
You should initialize the NSMutableDictionary using it's dictionary initializer, here's a quick example in Playground
let myDict:NSDictionary = ["a":1,"b":2]
let myMutableDict: NSMutableDictionary = NSMutableDictionary(dictionary: myDict)
myMutableDict["c"] = 3
myMutableDict["a"] // 1
myMutableDict["b"] // 2
myMutableDict["c"] // 3
Alternatively, you can declare a Swift dictionary as a var and mutate it whenever you want.
var swiftDictioanry : [String:AnyObject] = ["key":"value","key2":2]
The AnyObject value type mimics the behavior of an NSDictionary, if all types are known it can be declared like so:
var myNewSwiftDict : [String:String] = ["key":"value","nextKey":"nextValue"]
Related
I need to pass a Dictionary to a Objective-C method in Swift. In Swift the code is like this:
let modelData: Dictionary<String, [Double]> = getModelData()
result = myChilitags.estimate3D(configAt: configFilePath, forModel: modelData);
(The configure file has nothing to do with this problem, just ignore it.)
I used a .h file:
#interface myChilitags : NSObject
+ (nonnull UIImage *)estimate3D:configAt:(NSString *)configFilePath forModel:(nonnull NSDictionary*) modelData;
#end
The question is that I need to do something with the modelData in the Objective-C method estimate3D but I don't know what to do after I passed the Dictionary value modelData to the method.
I tried to just print the modelData value but all that came out was:
1
I also tried to print the value in the Dictionary like:
std::cout << modelData["face001"] << std::endl;
I am pretty sure that there is a key "face001" in the dictionary but the result was still:
1
I know it must have something to do with NSDictionary and Dictionary but I just don't know what to do.
First of all, a Dictionary in Swift is struct, an NSDictionary is class.
Objective-C is not type-safe so it doesn't show an error.
If you try to do the same in Swift, it will tell you
Cannot assign value of type '[String : [Double]]' to type 'NSDictionary'
let swiftDictionary = [String: [Double]]()
var nsDictionary = NSDictionary()
nsDictionary = swiftDictionary //shows error
So you have to convert the Swift dictionary to an NSDictionary.
let modelData: Dictionary<String, [Double]> = getModelData()
let nsModelData = NSDictionary(dictionary: modelData)
result = myChilitags.estimate3D(configAt: configFilePath, forModel: nsModelData);
I want to create a NSMutableDictionary using Swifty-Json.
I have declared dictionary like this
var arrTest = Array<JSON>()
var testDict : JSON = [:]
testDict.dictionaryObject?.updateValue(arrTest[0]["test"][indexPath.item]["xyz"], forKey: "abc")
Now I am unable to setValueForKey in this Dictionary.
Can Someone tell me how to create a NSMutableDictionary using SwiftyJson and also how to insert, update and delete values in this dictionary.
Thanks in advance
Don't use NSMutableDictionary in Swift, use Swift built-in type Dictionary instead. Declaring it as var will make it mutable.
You also don't use updateValue for Dictionary, simply use a subscript:
var testDict : [String : AnyObject] = [:]
let key = "abc"
let value = arrTest[0]["test"][indexPath.item]["xyz"]
testDict[key] = value
// add object
let testobj = ["qwe" : arrTest[0]["test"][indexPath.item]["xyz"]]
dictSelectedOption = JSON(testobj)
//remove objects
dictSelectedOption.dictionaryObject?.removeAll()
I've been recently trying to figure out how to init a Dictionary in swift like i used to do in Objective-c:
NSMutableDictionary *loginDictionary = [[NSMutableDictionary alloc] initWithObjects:#[UsernameTextfield.text,PasswordTextfield.text] forKeys:#[#"username",#"password"];
i tried to write it in Swift :
let userDictionary = NSMutableDictionary.init(object: [usernameTextField.text,passwordTextField.text], forKey: ["username","password"])
But i get an error:
Contextual type AnyObject cannot be used with array literal.
First of all, you have to use the same method, with objects and forKeys (note the plural).
Then you need to tell the compiler what type is each object, in your case it's strings from Optional text labels, so you could do something like this:
if let name = usernameTextField.text as? String, let pass = passwordTextField.text as? String {
let userDictionary = NSMutableDictionary(objects: [name, pass], forKeys: ["username", "password"])
}
You are Passing Objects and Keys in NSMutableDictionary as below, replace your code as below.
let userDictionary = NSMutableDictionary(objects: [usernameTextField.text,passwordTextField.text], forKeys: ["username","password"])
In the Swift PDF file released by Apple i came thorough this code
To create an empty array or dictionary, use the initializer syntax.
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
Here what is the use of creating a let (constant) object with empty array, where we cannot insert any values into it in next line ??!!
while teaching objective- c they start teaching like
NSArray *arrayObj = [[NSArray alloc] init]
if we declare like this we cannot add objects after initialisation
similarly they are teaching us how to initialise an array or dictionary objects
one more difference is if we allocate an empty array then we can assign another array with this.
let will not allow you to assign another array to it also
let emptyArray = [String]()
let/var filledArray = ["stack", "overflow"]
emptyArray = filledArray // will give you an error
Not much use, but the value can be copied:
let emptyDictionary = [String: Float]()
var otherDictionary = emptyDictionary
otherDictionary["a"] = 0.5
The property declaration sets them to a default, but you could actually change the value to something else in init. This would only be the case for class properties, not inline properties though.
Here's an example in a class scope where a let property can have a default but be changed:
class Whatever {
let testArray = [Int]()
init() {
testArray = [0,1,2]
}
}
So I have this NSDictionary itemsDict(in Swift):
var itemsDict : NSDictionary = [:] // Dictionary
var Sections : NSArray = [] // Array
itemsDict = [
["News"]:["a":"www.hello.co.uk","b":"www.hello.com"],
["Sport"]:["c":"www.hello.co.uk","d":"www.hello.com"],
]
print (itemsDict)
This is how the structure of the dictionary looks like:
{
(
News
) = {
a = "www.hello.co.uk";
b = "www.hello.com";
};
(
Sport
) = {
c = "www.hello.co.uk";
d = "www.hello.com";
};
}
From the dictionary above I want to be able to populate an NSArray with only the -
[News,Sports] elements.
I've tried this and a few other methods but they just don't seem to cut it. My Swift skills are not that advanced and I hope this post make sense.
Sections = itemsDict.allKeysForObject(<#anObject: AnyObject#>)
To get an Array of all Strings in your Dictionary's keys, you can use the allKeys property of NSDictionary along with a reduce function, like so:
var itemsDict = [
["News"]:["a":"www.hello.co.uk","b":"www.hello.com"],
["Sport"]:["c":"www.hello.co.uk","d":"www.hello.com"],
]
let keys = (itemsDict.allKeys as [[String]]).reduce([], combine: +)
println(keys)
Outputs:
[News, Sport]
However, I don't see a good reason to use Arrays of Strings as your Dictionary keys. Instead, I'd just use Strings as keys directly, like so:
var itemsDict = [
"News":["a":"www.hello.co.uk","b":"www.hello.com"],
"Sport":["c":"www.hello.co.uk","d":"www.hello.com"],
]
In which case, getting an Array of the Dictionary's keys is as simple as:
let keys = itemsDict.keys.array
Note: I'm using the keys property here and the allKeys property earlier because this is a native Swift Dictionary while the earlier code is an NSDictionary due to its use of NSArrays for keys.