[英]Append array int to a string array
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. 我想采取一个int数组并显示在同一行。 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. 所以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
}
}
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)
元组的序列转换为字符串数组。
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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.