ios - Remove a key from a dictionary for a given value -


how can remove key dictionary value x? need dictionary.removekeyforvalue(...) function.

i'd optimise following code. have text associated category , dictionary associates keywords categories. although text categorised i'd check whether should fall different category.

let text = "he said hello , ran away"    // taken "activity" category // dictionary associating keywords categories let categoryrules = ["hi" : "greeting", "hello" : "greeting", "jogging" : "activity", "joy" : "feeling"]  let keywords = array(categoryrules.keys) // make out of text array of words. let textwordarray = text.lowercasestring.characters.split{$0 == " "}.map(string.init)  // shouldn't have go through keys associated "activity" because text in it. keyword in keywords {          // if text contains rule     if let index = textwordarray.indexof(keyword) {         // associated category         if let category = categoryrules[keyword] {             print("the text should fall category of \(category)")             break         }     } } 

to remove keys dictionary value, can use for loop where clause select keys remove , assign nil remove them:

var categoryrules = ["hi" : "greeting", "hello" : "greeting", "jogging" : "activity", "joy" : "feeling"]  (key, value) in categoryrules value == "greeting" {     categoryrules[key] = nil }  print(categoryrules)  // ["jogging": "activity", "joy": "feeling"] 

you can add removekeysforvalue adding extension dictionary works values equatable (can compared ==):

extension dictionary value: equatable {     mutating func removekeysforvalue(value: value) {         (key, val) in self val == value {             self[key] = nil         }     } }  var categoryrules = ["hi" : "greeting", "hello" : "greeting", "jogging" : "activity", "joy" : "feeling"]  categoryrules.removekeysforvalue("greeting")  print(categoryrules)  // ["jogging": "activity", "joy": "feeling"] 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -