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

时间:2017-09-06 21:51:07

标签: ios arrays swift swift3

我有一个字符串数组,在单独的行上显示一个字符串。我想采取一个int数组并显示在同一行。因此,数组的条目按顺序配对。所以yourArray[1] = number[1]yourArray[2] = number[2]等等。所以我只想尝试将数字数组添加到labez.text = sortedArray.map { " ($0)" }.joined(separator:"\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 个答案:

答案 0 :(得分:3)

另一种方法是使用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"]

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

答案 1 :(得分:2)

以下是加入两个数组的方法:

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