Why I Can Not Use Setvalue for Dictionary

Why I can not use SetValue for Dictionary?

Swift dictionary does not have method like setValue:forKey:. Only NSMutableDictionary has such methods. If you wish to assign value for key in swift, you should use subscripting. Here is the correct way to do it, if you wish to do it with swift dictionary.

var imageDict:[String: String] = [:]

imageDict["\(tagValue)"] = NSStringFromCGRect(frame)

Or if you wish to use NSMutableDictionary then, it looks like this,

var imageDict = NSMutableDictionary()
imageDict.setObject(NSStringFromCGRect(frame), forKey: "\(tagValue)")

I get this error when I user dictionary `set value for key`

there are two basic errors in your code

first one: you have to use NSMutableDictionary, so change the line below

NSDictionary *dict = [NSDictionary dictionary];

to

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

then, the second one: you have to use the method setObject:forKey: (more at this link), so you should change the generic line below

[dict setValue:((Lucky28BuyCodeModel *)model).type forKey:@"code_type"];  

to

[dict setObject:((Lucky28BuyCodeModel *)model).type forKey:@"code_type"];  

finally, to "get" you have to use the method getObjectForKey: (more at this link)

Cannot set value to Dictionary Key

Instead of having the getter for the FullTime property return a new dictionary, you can, as of C# 6, provide a default value for the property like so:

public static Dictionary<string, ForecastType> FullTime {get;} = new Dictionary<string, ForecastType> () { /* initial dictionary values go here */ };

Swift, Firebase: `setValue` giving error AnyObject cannot be used with Dictionary Literal

  • ? is used if the value can become nil in the future.
  • ! is used if it really shouldn't become nil in the future, but it needs to be nil initially.

See the problem is Swift is a strictly typed language, if you declare a variable ? you are saying that it's of type nil. So a dictionary cant tell what type of a value would it be storing....

var myVar : String? // Look myVar, you and your type is completely nil as of now

var myVar : String! // Look myVar, your value is nil as of now but your type is certainly of String

Just change your code to this:-

     struct Pet {
var name:String!
var type:String!
var age:Int!
var feedingList:[String]
var walkingList:[String]
}

struct User {
var currentId:String?
var numberOfPets:Int?
var pets:[Pet]

}

class petBrain {

var reff = FIRDatabaseReference()
var currentUser:User = User(currentId: "",numberOfPets: 0,pets: [])

init(){
self.reff = FIRDatabase.database().reference()
}

func setUserId(cId:String?){
self.currentUser.currentId = cId
}

func addPet(newPet:Pet) {

let dict = ["name":newPet.name, "type":newPet.type, "age":newPet.age, "fList":newPet.feedingList, "wList":newPet.walkingList]

self.reff.child("pets").childByAutoId().setValue(dict)
}

}

Why doesn't setValue:forKeyPath invoked on mutable dictionary throw exception for unknown keypaths?

I can't find any documentation for this specific case, sorry, but my guess is that this:

[defs setValue:x forKeyPath:@"a.b.c"];

Is being implemented something like this:

[[defs objectForKey:@"a"] setValue:x forKeyPath:@"b.c"];

So objectForKey: returns nil, and methods called on nil just do nothing. That would explain the behaviour you have described.

NSMutableDictionary don't set value for key

dictionary = [NSMutableDictionary dictionary];
for(int x=0;x<[list count];x++){

NSString* key = [self getKeyForDate:list[x]];
NSMutableArray* listForMonth = dictionary[key];
if (key == nil) {
listForMonth = [NSMutableArray array];
[dictionary setValue:listForMonth forKey:key];
}
[listForMonth addObject:list[x]];
}

.....

In init

monthArray = @[@"January", @"February", @"March" ...

Separate method:

-(NSString*) getKeyForDate:(NSString*)date {
NSMutableArray *lstaInfo2 = [date componentsSeparatedByString:@"/"] mutableCopy];
NSInteger monthNum = lstaInfo2[0].integerValue;
NSString* result = [NSString stringWithFormat;@"%@ of %@", monthArray[monthNum-1], lstaInfo2[2]];
return result;
}

You can also use NSDateFormatter to parse the date, and NSCalendar to serve up the month names, but that's getting too deep for one lesson.

NSDictionary refuses to set values for its keys.

You have a comment stating

//Create a dictionary that holds the location data.

but you never actually create it.
Initialize the dictionary and you'll be fine.

self.placeDictionary = [NSMutableDictionary dictionary];

Also beware: setValue:forKey: is not the same as setObject:forKey:. Read this answer to know more on the subject, but in general you should use setObject:forKey: for dictionaries, e.g.

[self.placeDictionary setObject:@"155 Bovet Rd" forKey:@"Street"];

or the modern version of the syntax:

self.placeDictionary[@"Street"] = @"155 Bovet Rd";

Using Objective-C literals you can actually make the whole code a lot nicer, check it out:

self.placeDictionary = @{
@"Street": @"155 Bovet Rd",
@"City" : @"san mateo",
@"State" : @"ca",
@"ZIP" : @"94402"
};

Please note that the literal syntax produces a non-mutable dictionary and it may not fit your needs.

As a final remark, please don't use

[NSString stringWithFormat:@"aString"]

since is semantically equivalent to

@"aString"

but less optimized in terms of performances (not to mention code quality).

setvalue:forkey: not working, app is crashing

For of all you need to set testResult for objects and testArray for keys. Now if youIf you want to change the value of it you need to declare it as NSMutableDictionary.

NSMutableDictionary *testDetails = [NSMutableDictionary dictionaryWithObjects:testResult forKeys:testArray];
[testDetails setValue:@"Fail" forKey:@“Feb Month"];

Swift Set value in a Dictionary does not grow after first element added

The problem is that in Swift dictionaries and arrays are value types, not reference. So in your function follow when you do if var user = followees[followeeId] that variable is not a reference to the set in followees property, any insert you do over user is lost when the then scope ends.

You can rewrite your follow function like this:

public mutating func follow(_ followerId: Int, _ followeeId: Int){
if !followees.keys.contains(followeeId) {
followees[followeeId] = Set<Int>()
}
followees[followeeId]?.insert(followerId)
}


Related Topics



Leave a reply



Submit