[英]Swift Generic 2d Array
I'm looking to do something relatively simple. 我想做一些相对简单的事情。 I want a 2 dimension array of a generic type.
我想要一个通用类型的二维数组。 From what I understand, I should use two sets of square braces surrounding the base type, and I can use the simplified loop expression to init the values.
据我了解,我应该在基本类型周围使用两组方括号,并且可以使用简化的循环表达式来初始化值。 I have the below code, but I'm receiving an error,
cannot be constructed because it has no accessible initializes
. 我有下面的代码,但是我收到一个错误,
cannot be constructed because it has no accessible initializes
, cannot be constructed because it has no accessible initializes
。 Below is the code I'm using. 下面是我正在使用的代码。 Thank you in advance for any help.
预先感谢您的任何帮助。
array = [[Element]](count: 3, repeatedValue: Element(count: 2, repeatedValue: nil))
edit : I wanted to provide the full source of the code I'm working with 编辑:我想提供我正在使用的代码的完整源
struct Array2D<Element> {
let columns: Int
let rows: Int
private var array: Array<Element?>
init(columns: Int, rows: Int) {
self.columns = columns
self.rows = rows
array = [[Element]](count: 3, repeatedValue: Element(count: 2, repeatedValue: nil))
}
subscript(column: Int, row: Int) -> Element? {
get {
return array[row*columns + column]
}
set {
array[row*columns + column] = newValue
}
}
}
The 的
private var array: Array<Element?>
property in Array2D
is a normal ("one-dimensional") array used for the storage of the rows * columns
elements. Array2D
中的Array2D
是一个普通(“一维”)数组,用于存储rows * columns
元素。 It must be initialized with: 必须使用以下命令初始化它:
array = [Element?](count: rows * columns, repeatedValue: nil)
or just (because the type is known): 或者只是(因为类型已知):
array = Array(count: rows * columns, repeatedValue: nil)
Swift doesn't know Element
has an intializer for the Element
type. Swift不知道
Element
具有Element
类型的初始化器。
Here's how you can do it with a helper class: 这是您可以通过帮助程序类完成的操作:
class TwoDArray<T> {
static func create(initialValue: T, rows: Int, cols: Int) -> [[T]] {
let tmp = [T](count: cols, repeatedValue: initialValue)
return [[T]](count: rows, repeatedValue: tmp)
}
}
let result = TwoDArray.create(42, rows: 3, cols: 2)
If you want to initiate the array with nil
, you have to supply an optional type: 如果要使用
nil
初始化数组,则必须提供一个可选类型:
let result = TwoDArray<Int?>.create(nil, rows: 3, cols: 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.