title: Swift: safely convert list of comma-separated numbers in a string to an array of Ints
body: <p>I would like to create an array of integers, [Int] from a string which should contain a list comma seperated numbers.</p>
  
  <p>Here are some valid inputs:</p>
  
  <pre><code>1
  1,2,3
  1,5,10
  </code></pre>
  
  <p>Here are some invalid inputs:</p>
  
  <pre><code>[nil] // no value set
  1,,2,3 // extra commas
  1,Z,10 // characters other than numbers and commas
  </code></pre>
  
  <p>I've managed to come up with something for the first part, i.e. separating the values out, using this code:</p>
  
  <pre><code>func get_numbers() -&gt; Array&lt;Int&gt;{
      return self.numbers_as_csv_string!
          .components(separatedBy: ",")
          .map { word in Int(word.trimmingCharacters(in: CharacterSet.whitespaces))! }
  }
  </code></pre>
  
  <p>Unfortunately, that code doesn't deal with invalid inputs as listed above and the app will just crash in most cases. What is the best way of adding in some checks to this, so that if an invalid list is present, we just return a <code>[1]</code>? I'd like the shortest code possible - is a regex the best way to go here?</p>
  
  <p>Many thanks in advance!</p>