title: How can I change the contrast every time the user selects another color?
body: <p>I know that in JavaScript exists a function which changes the contrast depending on which color is currently selected:</p>
  
  <hr>
  
  <pre class="lang-js prettyprint-override"><code>function getHigherContrast(r, g, b) {
      const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
      return (yiq &gt;= 128) ? '#000000' : '#FFFFFF';
  }
  </code></pre>
  
  <p>How can I rewrite this function to Swift-Code so that the contrast changes every time the user selects another color:
  <a href="https://i.stack.imgur.com/X21iP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X21iP.png" alt="enter image description here"></a></p>
  
  <hr>
  
  <pre><code>override func viewDidLoad() {
      super.viewDidLoad()
  
      self.view.addSubview(colorPicker)
      colorPicker.translatesAutoresizingMaskIntoConstraints = false
      colorPicker.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor).isActive = true
      colorPicker.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor).isActive = true
      colorPicker.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor).isActive = true
      colorPicker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
  
      navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action:#selector(handleDone(sender:)))
  
      colors.append((colorTitle: "rot", color: UIColor.red))
      colors.append((colorTitle: "gelb", color: UIColor.yellow))
      colors.append((colorTitle: "grün", UIColor.green))
      colors.append((colorTitle: "schwarz", UIColor.black))
  
      colorPicker.delegate = self
      colorPicker.dataSource = self
  }
  
  func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {
      return 1
  }
  
  func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {
      return colors.count
  }
  
  func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -&gt; NSAttributedString? {
      return NSAttributedString(string: colors[row].colorTitle, attributes: [NSAttributedStringKey.foregroundColor: colors[row].color])
  }
  
  @objc func handleDone(sender: AnyObject?) {
      if let d = delegate {
          d.colorPicked(color: colors[colorPicker.selectedRow(inComponent: 0)].color)
      }
      dismiss(animated: true)
  }
  </code></pre>
  
  <hr>
  
  <p><a href="https://pastebin.com/M7jUpHSg" rel="nofollow noreferrer">Here</a> is the full source code for the class.</p>