mohammy52
mohammy52

Reputation: 13

Extracting a value from a Dictionary in Swift

Aim: If the input in text1 matches with a value in superDictionary,then a second dictionary (that corresponds with that value which matched) has it's values multiplied by the number value in num1 WHEN button1 is pressed (a mouthful I know)

e.g. if text1.text = "apple" (which matches with a value in superDictionary) (see in code below), then that match redirects me to appleDictionary whose every entry then becomes multiplied by the number value in num1 (say 5) when button1 is pressed.

The problem: I don't know what syntax to use to do this!

My IBOutlets and IBActions are as follows:

@IBOutlet weak var text1: UITextField!

@IBOutlet weak var num1: UITextField!

var superDictionary = ["apple","banana"]

var appleDictionary = ["fibre": 1, "water": 2]

@IBAction func button1(sender: AnyObject) {}

Thanks in advance

Upvotes: 1

Views: 120

Answers (1)

vacawama
vacawama

Reputation: 154613

I would suggest that you combine your dictionaries and make a true superDictionary:

var superDictionary = ["apple": ["fibre": 1, "water": 2], "banana": ["potassium": 2, "water": 2]]

Then your button action would be something like this:

@IBAction func button1(sender: AnyObject) {
    guard let num = Int(num1.text ?? "") else { return }
    guard let text = text1.text else { return }
    guard var dict = superDictionary[text] else { return }

    for (key, value) in dict {
        dict[key] = value * num
    }

    superDictionary[text] = dict
}

Notes:

  • The first guard statement extracts num from the num1 textField. If the textField is nil the nil coalescing operator ?? turns it into an empty String which Int makes into nil. If there is a string that can successfully be converted to an Int, the guard statement succeeds and assigns it to num, otherwise the function returns.
  • The second guard statement assigns the string in text1.text to text or returns if the textField is nil.
  • The third guard statement assigns the proper dictionary to dict if it exists, or returns if there is no such dictionary. This guard uses var instead of let because we will be modifying this dictionary.
  • The loop modifies the dictionary by extracting key/value pairs and by replacing the value with value * num.
  • The final assignment replaces the dictionary in the superDictionary with the modified one.

Upvotes: 1

Related Questions