3

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 
  }

}
1
  • There might be a clever use of map available, but you could also just go old school and use a for loop to enumerate both arrays at the same time. Commented Sep 6, 2017 at 21:58

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

let list = zip(a, b).map { "\($0) \($1)" }
Nice one, don't know how I missed it @vacawama, but thanks for pointing it out.
2

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"]

4 Comments

Will this still work if the string array has dupes? And is performance an issue by using indexOf so frequently?
Good point @conarch, dupes are a problem, will fix shortly. Regarding indexOf I think you need to check on real data, otherwise feels like premature optimization.
@conarch I edited my answer, what do you think? Works with dupes and doesn't use indexOf
Nice @njuri! I'm glad I looked at this question, because I learned something new. :-)