将数组int追加到字符串数组中

时间:2021-03-25 21:35:00

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.

我有一个字符串数组,在单独的行上显示一个字符串。我想采取一个int数组并显示在同一行。因此,数组的条目按顺序配对。所以yourArray [1] =数字[1],yourArray [2] =数字[2]等等。所以我只想尝试将数字数组添加到labez.text = sortedArray.map {“($ 0)”}。已加入(分隔符:“\ n”)代码行。

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 
  }

}

2 个解决方案

#1


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

#2


3  

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

另一种方法是使用zip功能,你可以在游乐场尝试:

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.

我正在ziping两个数组,它返回一个序列,然后使用reduce方法将(String,Int)元组的序列转换为字符串数组。

#1


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

#2


3  

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

另一种方法是使用zip功能,你可以在游乐场尝试:

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.

我正在ziping两个数组,它返回一个序列,然后使用reduce方法将(String,Int)元组的序列转换为字符串数组。