Two-dimensional array in Swift
up vote
73
down vote
favorite
I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.
First of all; declaration of an empty array:
class test{
var my2Darr = Int()
}
Secondly fill the array. (such as my2Darr[i][j] = 0
where i, j are for-loop variables)
class test {
var my2Darr = Int()
init() {
for(var i:Int=0;i<10;i++) {
for(var j:Int=0;j<10;j++) {
my2Darr[i][j]=18 /* Is this correct? */
}
}
}
}
And Lastly, Editing element of in array
class test {
var my2Darr = Int()
init() {
.... //same as up code
}
func edit(number:Int,index:Int){
my2Darr[index][index] = number
// Is this correct? and What if index is bigger
// than i or j... Can we control that like
if (my2Darr[i][j] == nil) { ... } */
}
}
arrays swift
add a comment |
up vote
73
down vote
favorite
I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.
First of all; declaration of an empty array:
class test{
var my2Darr = Int()
}
Secondly fill the array. (such as my2Darr[i][j] = 0
where i, j are for-loop variables)
class test {
var my2Darr = Int()
init() {
for(var i:Int=0;i<10;i++) {
for(var j:Int=0;j<10;j++) {
my2Darr[i][j]=18 /* Is this correct? */
}
}
}
}
And Lastly, Editing element of in array
class test {
var my2Darr = Int()
init() {
.... //same as up code
}
func edit(number:Int,index:Int){
my2Darr[index][index] = number
// Is this correct? and What if index is bigger
// than i or j... Can we control that like
if (my2Darr[i][j] == nil) { ... } */
}
}
arrays swift
Are you having problems with your approach?
– Alex Wayne
Aug 4 '14 at 21:22
2
Just so you know, your entire second step can be reduced down to thisvar my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))
And you should really upgrade to a newer beta.Int()
is no longer valid syntax. It's been changed to[[Int]]()
.
– Mick MacCallum
Aug 4 '14 at 21:23
1
The 2D init using repeated values won't work. All the rows will point to the same sub-array, and thus no be uniquely writable.
– hotpaw2
Aug 4 '14 at 21:26
@0x7fffffff; Thank you, this was the what i am looking for...
– Antiokhos
Aug 4 '14 at 21:39
add a comment |
up vote
73
down vote
favorite
up vote
73
down vote
favorite
I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.
First of all; declaration of an empty array:
class test{
var my2Darr = Int()
}
Secondly fill the array. (such as my2Darr[i][j] = 0
where i, j are for-loop variables)
class test {
var my2Darr = Int()
init() {
for(var i:Int=0;i<10;i++) {
for(var j:Int=0;j<10;j++) {
my2Darr[i][j]=18 /* Is this correct? */
}
}
}
}
And Lastly, Editing element of in array
class test {
var my2Darr = Int()
init() {
.... //same as up code
}
func edit(number:Int,index:Int){
my2Darr[index][index] = number
// Is this correct? and What if index is bigger
// than i or j... Can we control that like
if (my2Darr[i][j] == nil) { ... } */
}
}
arrays swift
I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong.
First of all; declaration of an empty array:
class test{
var my2Darr = Int()
}
Secondly fill the array. (such as my2Darr[i][j] = 0
where i, j are for-loop variables)
class test {
var my2Darr = Int()
init() {
for(var i:Int=0;i<10;i++) {
for(var j:Int=0;j<10;j++) {
my2Darr[i][j]=18 /* Is this correct? */
}
}
}
}
And Lastly, Editing element of in array
class test {
var my2Darr = Int()
init() {
.... //same as up code
}
func edit(number:Int,index:Int){
my2Darr[index][index] = number
// Is this correct? and What if index is bigger
// than i or j... Can we control that like
if (my2Darr[i][j] == nil) { ... } */
}
}
arrays swift
arrays swift
edited Jul 23 '17 at 15:31
ROMANIA_engineer
32.3k19143141
32.3k19143141
asked Aug 4 '14 at 21:17
Antiokhos
1,03031824
1,03031824
Are you having problems with your approach?
– Alex Wayne
Aug 4 '14 at 21:22
2
Just so you know, your entire second step can be reduced down to thisvar my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))
And you should really upgrade to a newer beta.Int()
is no longer valid syntax. It's been changed to[[Int]]()
.
– Mick MacCallum
Aug 4 '14 at 21:23
1
The 2D init using repeated values won't work. All the rows will point to the same sub-array, and thus no be uniquely writable.
– hotpaw2
Aug 4 '14 at 21:26
@0x7fffffff; Thank you, this was the what i am looking for...
– Antiokhos
Aug 4 '14 at 21:39
add a comment |
Are you having problems with your approach?
– Alex Wayne
Aug 4 '14 at 21:22
2
Just so you know, your entire second step can be reduced down to thisvar my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))
And you should really upgrade to a newer beta.Int()
is no longer valid syntax. It's been changed to[[Int]]()
.
– Mick MacCallum
Aug 4 '14 at 21:23
1
The 2D init using repeated values won't work. All the rows will point to the same sub-array, and thus no be uniquely writable.
– hotpaw2
Aug 4 '14 at 21:26
@0x7fffffff; Thank you, this was the what i am looking for...
– Antiokhos
Aug 4 '14 at 21:39
Are you having problems with your approach?
– Alex Wayne
Aug 4 '14 at 21:22
Are you having problems with your approach?
– Alex Wayne
Aug 4 '14 at 21:22
2
2
Just so you know, your entire second step can be reduced down to this
var my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))
And you should really upgrade to a newer beta. Int()
is no longer valid syntax. It's been changed to [[Int]]()
.– Mick MacCallum
Aug 4 '14 at 21:23
Just so you know, your entire second step can be reduced down to this
var my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))
And you should really upgrade to a newer beta. Int()
is no longer valid syntax. It's been changed to [[Int]]()
.– Mick MacCallum
Aug 4 '14 at 21:23
1
1
The 2D init using repeated values won't work. All the rows will point to the same sub-array, and thus no be uniquely writable.
– hotpaw2
Aug 4 '14 at 21:26
The 2D init using repeated values won't work. All the rows will point to the same sub-array, and thus no be uniquely writable.
– hotpaw2
Aug 4 '14 at 21:26
@0x7fffffff; Thank you, this was the what i am looking for...
– Antiokhos
Aug 4 '14 at 21:39
@0x7fffffff; Thank you, this was the what i am looking for...
– Antiokhos
Aug 4 '14 at 21:39
add a comment |
6 Answers
6
active
oldest
votes
up vote
165
down vote
accepted
Define mutable array
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] =
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
Change element at position
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
Change sub array
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
Examine size/bounds before access
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks:
Same markup rules for 3 and N dimensional arrays.
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
If you havearr
defined as in the answer thenmyVar
should be Int, is it?
– Keenle
Aug 5 '14 at 10:25
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
5
In Swift 3, for copy pasters:var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
|
show 4 more comments
up vote
22
down vote
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
add a comment |
up vote
8
down vote
You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24)
.
If the value is an object, which is initialized by MyClass()
, then they will use the same reference.
Array(repeating: Array(repeating: MyClass(), count: 80), count: 24)
doesn't create a new instance of MyClass
in each array element. This method only creates MyClass
once and puts it into the array.
Here's a safe way to initialize a multidimensional array.
private var matrix: [[MyClass]] = MyClass.newMatrix()
private static func newMatrix() -> [[MyClass]] {
var matrix: [[MyClass]] =
for i in 0...23 {
matrix.append( )
for _ in 0...79 {
matrix[i].append( MyClass() )
}
}
return matrix
}
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Good point about the problem with reference types. However, why do you writeArray(repeating: {value}, could 80)
with braces around{value}
? That would create an array of closures, would it not?
– Duncan C
Sep 11 at 0:25
Or is{value}
meta-notation for "some value of type AnyObject" (a reference type)?
– Duncan C
Sep 11 at 0:26
add a comment |
up vote
6
down vote
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
1
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
1
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
1
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array usingArray(repeating:count:)
. See the comment I posted to your other answer.
– Duncan C
Sep 11 at 0:39
add a comment |
up vote
4
down vote
In Swift 4
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
add a comment |
up vote
2
down vote
Make it Generic Swift 4
struct Matrix<T> {
let rows: Int, columns: Int
var grid: [T]
init(rows: Int, columns: Int,defaultValue: T) {
self.rows = rows
self.columns = columns
grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)
matrix[0,10] = true
print(matrix[0,10])
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
165
down vote
accepted
Define mutable array
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] =
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
Change element at position
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
Change sub array
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
Examine size/bounds before access
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks:
Same markup rules for 3 and N dimensional arrays.
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
If you havearr
defined as in the answer thenmyVar
should be Int, is it?
– Keenle
Aug 5 '14 at 10:25
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
5
In Swift 3, for copy pasters:var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
|
show 4 more comments
up vote
165
down vote
accepted
Define mutable array
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] =
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
Change element at position
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
Change sub array
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
Examine size/bounds before access
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks:
Same markup rules for 3 and N dimensional arrays.
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
If you havearr
defined as in the answer thenmyVar
should be Int, is it?
– Keenle
Aug 5 '14 at 10:25
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
5
In Swift 3, for copy pasters:var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
|
show 4 more comments
up vote
165
down vote
accepted
up vote
165
down vote
accepted
Define mutable array
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] =
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
Change element at position
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
Change sub array
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
Examine size/bounds before access
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks:
Same markup rules for 3 and N dimensional arrays.
Define mutable array
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] =
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
Change element at position
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
Change sub array
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
Examine size/bounds before access
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks:
Same markup rules for 3 and N dimensional arrays.
edited Mar 22 at 19:45
Aron
2,29521838
2,29521838
answered Aug 4 '14 at 21:57
Keenle
9,60222745
9,60222745
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
If you havearr
defined as in the answer thenmyVar
should be Int, is it?
– Keenle
Aug 5 '14 at 10:25
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
5
In Swift 3, for copy pasters:var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
|
show 4 more comments
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
If you havearr
defined as in the answer thenmyVar
should be Int, is it?
– Keenle
Aug 5 '14 at 10:25
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
5
In Swift 3, for copy pasters:var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
ok one dumy question: how we assign that array, In C we do like that: arr[i][j]=myVar; but in swift when i try to do same way I got this error " '[([(Int)])].Type' does not have a member named 'subscript' "
– Antiokhos
Aug 5 '14 at 9:56
If you have
arr
defined as in the answer then myVar
should be Int, is it?– Keenle
Aug 5 '14 at 10:25
If you have
arr
defined as in the answer then myVar
should be Int, is it?– Keenle
Aug 5 '14 at 10:25
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
yes it is int. And thank you very much for detailed answer.. now its clear:D
– Antiokhos
Aug 5 '14 at 10:40
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
Trying to figure out if I need to add anything else to the answer... Does latest update to the answer clarify what you've asked in the comment?
– Keenle
Aug 5 '14 at 10:44
5
5
In Swift 3, for copy pasters:
var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
In Swift 3, for copy pasters:
var arr = Int(repeating: Int(repeating: 0, count: 2), count: 3)
– kar
Jan 9 '17 at 11:53
|
show 4 more comments
up vote
22
down vote
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
add a comment |
up vote
22
down vote
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
add a comment |
up vote
22
down vote
up vote
22
down vote
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
From the docs:
You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:
var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.
answered Aug 4 '14 at 21:25
Woodstock
12.4k1261100
12.4k1261100
add a comment |
add a comment |
up vote
8
down vote
You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24)
.
If the value is an object, which is initialized by MyClass()
, then they will use the same reference.
Array(repeating: Array(repeating: MyClass(), count: 80), count: 24)
doesn't create a new instance of MyClass
in each array element. This method only creates MyClass
once and puts it into the array.
Here's a safe way to initialize a multidimensional array.
private var matrix: [[MyClass]] = MyClass.newMatrix()
private static func newMatrix() -> [[MyClass]] {
var matrix: [[MyClass]] =
for i in 0...23 {
matrix.append( )
for _ in 0...79 {
matrix[i].append( MyClass() )
}
}
return matrix
}
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Good point about the problem with reference types. However, why do you writeArray(repeating: {value}, could 80)
with braces around{value}
? That would create an array of closures, would it not?
– Duncan C
Sep 11 at 0:25
Or is{value}
meta-notation for "some value of type AnyObject" (a reference type)?
– Duncan C
Sep 11 at 0:26
add a comment |
up vote
8
down vote
You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24)
.
If the value is an object, which is initialized by MyClass()
, then they will use the same reference.
Array(repeating: Array(repeating: MyClass(), count: 80), count: 24)
doesn't create a new instance of MyClass
in each array element. This method only creates MyClass
once and puts it into the array.
Here's a safe way to initialize a multidimensional array.
private var matrix: [[MyClass]] = MyClass.newMatrix()
private static func newMatrix() -> [[MyClass]] {
var matrix: [[MyClass]] =
for i in 0...23 {
matrix.append( )
for _ in 0...79 {
matrix[i].append( MyClass() )
}
}
return matrix
}
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Good point about the problem with reference types. However, why do you writeArray(repeating: {value}, could 80)
with braces around{value}
? That would create an array of closures, would it not?
– Duncan C
Sep 11 at 0:25
Or is{value}
meta-notation for "some value of type AnyObject" (a reference type)?
– Duncan C
Sep 11 at 0:26
add a comment |
up vote
8
down vote
up vote
8
down vote
You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24)
.
If the value is an object, which is initialized by MyClass()
, then they will use the same reference.
Array(repeating: Array(repeating: MyClass(), count: 80), count: 24)
doesn't create a new instance of MyClass
in each array element. This method only creates MyClass
once and puts it into the array.
Here's a safe way to initialize a multidimensional array.
private var matrix: [[MyClass]] = MyClass.newMatrix()
private static func newMatrix() -> [[MyClass]] {
var matrix: [[MyClass]] =
for i in 0...23 {
matrix.append( )
for _ in 0...79 {
matrix[i].append( MyClass() )
}
}
return matrix
}
You should be careful when you're using Array(repeating: Array(repeating: {value}, count: 80), count: 24)
.
If the value is an object, which is initialized by MyClass()
, then they will use the same reference.
Array(repeating: Array(repeating: MyClass(), count: 80), count: 24)
doesn't create a new instance of MyClass
in each array element. This method only creates MyClass
once and puts it into the array.
Here's a safe way to initialize a multidimensional array.
private var matrix: [[MyClass]] = MyClass.newMatrix()
private static func newMatrix() -> [[MyClass]] {
var matrix: [[MyClass]] =
for i in 0...23 {
matrix.append( )
for _ in 0...79 {
matrix[i].append( MyClass() )
}
}
return matrix
}
edited Mar 2 at 8:59
Ian
53
53
answered Sep 16 '17 at 7:12
Kimi Chiu
1,08011324
1,08011324
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Good point about the problem with reference types. However, why do you writeArray(repeating: {value}, could 80)
with braces around{value}
? That would create an array of closures, would it not?
– Duncan C
Sep 11 at 0:25
Or is{value}
meta-notation for "some value of type AnyObject" (a reference type)?
– Duncan C
Sep 11 at 0:26
add a comment |
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Good point about the problem with reference types. However, why do you writeArray(repeating: {value}, could 80)
with braces around{value}
? That would create an array of closures, would it not?
– Duncan C
Sep 11 at 0:25
Or is{value}
meta-notation for "some value of type AnyObject" (a reference type)?
– Duncan C
Sep 11 at 0:26
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Hi can we improve that as an extension with "anyObject" type?
– Antiokhos
Aug 19 at 6:40
Good point about the problem with reference types. However, why do you write
Array(repeating: {value}, could 80)
with braces around {value}
? That would create an array of closures, would it not?– Duncan C
Sep 11 at 0:25
Good point about the problem with reference types. However, why do you write
Array(repeating: {value}, could 80)
with braces around {value}
? That would create an array of closures, would it not?– Duncan C
Sep 11 at 0:25
Or is
{value}
meta-notation for "some value of type AnyObject" (a reference type)?– Duncan C
Sep 11 at 0:26
Or is
{value}
meta-notation for "some value of type AnyObject" (a reference type)?– Duncan C
Sep 11 at 0:26
add a comment |
up vote
6
down vote
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
1
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
1
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
1
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array usingArray(repeating:count:)
. See the comment I posted to your other answer.
– Duncan C
Sep 11 at 0:39
add a comment |
up vote
6
down vote
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
1
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
1
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
1
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array usingArray(repeating:count:)
. See the comment I posted to your other answer.
– Duncan C
Sep 11 at 0:39
add a comment |
up vote
6
down vote
up vote
6
down vote
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Link: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
answered Apr 9 at 14:30
Keyhan Kamangar
9117
9117
1
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
1
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
1
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array usingArray(repeating:count:)
. See the comment I posted to your other answer.
– Duncan C
Sep 11 at 0:39
add a comment |
1
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
1
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
1
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array usingArray(repeating:count:)
. See the comment I posted to your other answer.
– Duncan C
Sep 11 at 0:39
1
1
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
I like it. It's reminiscent of C pointer arithmetic. It would be better if rewritten using Generics though, so it would apply to 2-dimensional arrays of any data type. For that matter, you could use this approach to create arrays any arbitrary dimension.
– Duncan C
Sep 10 at 23:51
1
1
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
@DuncanC, stackoverflow.com/a/51448698/1630618
– vacawama
Sep 11 at 0:05
1
1
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array using
Array(repeating:count:)
. See the comment I posted to your other answer.– Duncan C
Sep 11 at 0:39
@vacawama, cool, except your n-dimensional array has the same problem as all the solutions that populate the array using
Array(repeating:count:)
. See the comment I posted to your other answer.– Duncan C
Sep 11 at 0:39
add a comment |
up vote
4
down vote
In Swift 4
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
add a comment |
up vote
4
down vote
In Swift 4
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
add a comment |
up vote
4
down vote
up vote
4
down vote
In Swift 4
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
In Swift 4
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
// [[0, 0], [0, 0], [0, 0]]
edited May 16 at 13:27
Marko Nikolovski
3,2712535
3,2712535
answered Aug 27 '17 at 18:39
Ankit garg
1,005814
1,005814
add a comment |
add a comment |
up vote
2
down vote
Make it Generic Swift 4
struct Matrix<T> {
let rows: Int, columns: Int
var grid: [T]
init(rows: Int, columns: Int,defaultValue: T) {
self.rows = rows
self.columns = columns
grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)
matrix[0,10] = true
print(matrix[0,10])
add a comment |
up vote
2
down vote
Make it Generic Swift 4
struct Matrix<T> {
let rows: Int, columns: Int
var grid: [T]
init(rows: Int, columns: Int,defaultValue: T) {
self.rows = rows
self.columns = columns
grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)
matrix[0,10] = true
print(matrix[0,10])
add a comment |
up vote
2
down vote
up vote
2
down vote
Make it Generic Swift 4
struct Matrix<T> {
let rows: Int, columns: Int
var grid: [T]
init(rows: Int, columns: Int,defaultValue: T) {
self.rows = rows
self.columns = columns
grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)
matrix[0,10] = true
print(matrix[0,10])
Make it Generic Swift 4
struct Matrix<T> {
let rows: Int, columns: Int
var grid: [T]
init(rows: Int, columns: Int,defaultValue: T) {
self.rows = rows
self.columns = columns
grid = Array(repeating: defaultValue, count: rows * columns) as! [T]
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> T {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix:Matrix<Bool> = Matrix(rows: 1000, columns: 1000,defaultValue:false)
matrix[0,10] = true
print(matrix[0,10])
answered Nov 21 at 22:46
dimo hamdy
1,0691211
1,0691211
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f25127700%2ftwo-dimensional-array-in-swift%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Are you having problems with your approach?
– Alex Wayne
Aug 4 '14 at 21:22
2
Just so you know, your entire second step can be reduced down to this
var my2DArray = Array(count: 10, repeatedValue: Array(count: 10, repeatedValue: 18))
And you should really upgrade to a newer beta.Int()
is no longer valid syntax. It's been changed to[[Int]]()
.– Mick MacCallum
Aug 4 '14 at 21:23
1
The 2D init using repeated values won't work. All the rows will point to the same sub-array, and thus no be uniquely writable.
– hotpaw2
Aug 4 '14 at 21:26
@0x7fffffff; Thank you, this was the what i am looking for...
– Antiokhos
Aug 4 '14 at 21:39