[英]Convert [Int] to (Int) and vice-versa in swift
How can I convert an int array 我如何转换一个int数组
let beforeSorting = [1, 2, 3, 4, 0, 6, 7, 8, 9, 10]
to 至
(1, 2, 3, 4, 0, 6, 7, 8, 9, 10)
Also in reverse in swift? 还迅速反过来?
var a: Int = 0
var b: Int = 0
var c: Int = 0
..likewise 20 variables
I wanted to apply some operations to these values, so I converted the values into array like 我想对这些值进行一些操作,所以我将这些值转换成数组,例如
let array = [a, b, c,..] // counting 20 elements
After applying some operations like sorting. 应用诸如排序之类的一些操作之后。 I need to put these values back to the properties. 我需要将这些值放回属性。
So I made an tuple with these properties. 所以我用这些属性做了一个元组。 Here is my problem. 这是我的问题。 how can I assign my new array to tuple. 如何将新数组分配给元组。 (Setting all properties at once) (一次设置所有属性)
just like (a, b, c, d..) = myarray
就像(a, b, c, d..) = myarray
Tuples must have a predefined size and type. 元组必须具有预定义的大小和类型。 So all you can do is have some convenience which may be done on many ways. 因此,您所能做的就是有一些便利,可以通过多种方式完成。 You could for instance create a wrapper: 例如,您可以创建一个包装器:
typealias MyTuple = (a: Int, b: Int, c: Int, d: Int, e: Int, f: Int)
class ToupleWrapper {
private var values: [Int]
init(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int) {
values = [a, b, c, d, e, f]
}
convenience init(array: [Int]) {
self.init(a: array[0], b: array[1], c: array[2], d: array[3], e: array[4], f: array[5])
}
convenience init(tuple: MyTuple) {
self.init(a: tuple.a, b: tuple.b, c: tuple.c, d: tuple.d, e: tuple.e, f: tuple.f)
}
var array: [Int] {
return values
}
var tuple: MyTuple {
return (values[0], values[1], values[2], values[3], values[4], values[5])
}
}
And usage: 和用法:
func foo() {
let arrayFromValue = ToupleWrapper(a: 3, b: 2, c: 1, d: 4, e: 2, f: 2).array
let arrayFromTouple = ToupleWrapper(tuple: (0, 1, 3, 2, 4, 2)).array
let tupleFromArray = ToupleWrapper(array: [2, 3, 1, 4, 2, 2]).tuple
}
No, you cannot do this in a safe manner. 不,您不能安全地执行此操作。 A tuple has a fixed length that is known at compile time, while the length on an array is something obtained at runtime. 元组具有在编译时已知的固定长度,而数组上的长度是在运行时获得的。
Converting a tuple into an array is possible, but only if all tuple elements are of the same type or have a common type - you can simply reference the .0 ... .10 elements of it. 将元组转换为数组是可能的,但是仅当所有元组元素具有相同类型或具有共同类型时,您才可以简单地引用它的.0 ... .10元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.