title: How can I simplify this Swift sorting code?
body: <p>I'm working through a <a href="https://www.raywenderlich.com/143828/macos-nstableview-tutorial" rel="nofollow noreferrer">tutorial on NSTableView</a> with my own data. I've gotten to the point where I'm writing my sorting function, and this is what I've come up with:</p>
  
  <pre><code>var payment_list: [Payment]!
  
  func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) {
      guard let sortDescriptor = tableView.sortDescriptors.first else {
          return
      }
  
      let key = sortDescriptor.key!
  
      if sortDescriptor.ascending == true {
          if key == "id" {
              payment_list.sort { $0.id &lt; $1.id }
          } else if key == "msatoshi" {
              payment_list.sort { $0.msatoshi &lt; $1.msatoshi }
          } else if key == "created_at" {
              payment_list.sort { $0.created_at &lt; $1.created_at }
          } else if key == "status" {
              payment_list.sort { $0.status &lt; $1.status }
          }
      } else {
          if key == "id" {
              payment_list.sort(by: { $0.id &gt; $1.id })
          } else if key == "msatoshi" {
              payment_list.sort { $0.msatoshi &gt; $1.msatoshi }
          } else if key == "created_at" {
              payment_list.sort { $0.created_at &gt; $1.created_at }
          } else if key == "status" {
              payment_list.sort { $0.status &gt; $1.status }
          }
      }
  
      tableView.reloadData()
  }
  </code></pre>
  
  <p>It works fine, but I can't help but thinking that this is pretty verbose for something as common as sorting a multi-column list. The actual list in my app has several additional columns.</p>
  
  <p>Are there any Swift tricks that I can use to make this code a bit more concise? Something like this would be more desirable:</p>
  
  <pre><code>if sortDescriptor.ascending == true {
      payment_list.sort($0[key] &lt; $1[key])
  } else {
      payment_list.sort($0[key] &gt; $1[key])
  }
  </code></pre>
  
  <p>Or maybe even something like:</p>
  
  <pre><code>payment_list = payment_list.sort(by: key, order: "ASC")
  </code></pre>
  
  <p>I get the impression that there are a lot of giant nested <code>if...else if</code> and/or <code>switch...case</code> blocks involved in Swift development. Is that an accurate assessment?</p>
  
  <p><strong>Update</strong>:</p>
  
  <p>This is my <code>Payment</code> definition:</p>
  
  <pre><code>struct Payment: Codable, PaymentFactory {
      let id: Int
      let payment_hash: String
      let destination: String
      let msatoshi: Int
      let timestamp: Int
      let created_at: Int
      let status: String
  
      enum PaymentKeys: String, CodingKey {
          case payments
      }
  
      static func fake() -&gt; Payment {
          // snipped for brevity
      }
  }
  </code></pre>