Question: Append array int to a string array

Question

Append array int to a string array

Answers 2
Added at 2017-09-06 23:09
Tags
Question

I have a string array that displays a string on an individual line. I would like to take an int array and display on the same line. So the entries of the array are paired in order. So yourArray[1] = number[1], yourArray[2] = number[2], etc. So I am just trying to add a the number array to labez.text = sortedArray.map { " ($0)" }.joined(separator:"\n") line of code.

var yourArray = [String]()
var number = [Int]()


@IBAction func store(_ sender: Any) {
  yourArray.append((textA.text!))
  number.append(Int(textB.text!)!)

  labez.text = sortedArray.map { " \($0)" }.joined(separator:"\n")


  let sortedArray:[String] = yourArray.sorted {
    $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending 
  }

}
Answers to

Append array int to a string array

nr: #1 dodano: 2017-09-06 23:09

Here's how you can join two arrays:

let a = ["a","b","c","b"]
let b = [1,2,3,4]

let d = a.enumerated().map { (index,string) -> String in
  guard  b.count > index else { return "" }
  return "\(b[index]) \(string)"
}

// d = ["1 a", "2 b", "3 c", "4 b"]
nr: #2 dodano: 2017-09-07 00:09

Another way to do this is with the zip function, you can try this in a playground:

let a = ["a","b","c","b"]
let b = [1,2,3,4]

let list = zip(a, b).map{ $0 + " \($1)" }

list // -> ["a 1", "b 2", "c 3", "b 4"]

I'm ziping the two arrays, which returns a sequence, and then using the reduce method to transform the sequence of (String, Int) tuples into a string array.

Source Show
◀ Wstecz