Swift - Arrays: Unterschied zwischen den Versionen

Aus Wikizone
Wechseln zu: Navigation, Suche
Zeile 1: Zeile 1:
 +
== Links ==
 +
[[Swift (Programmiersprache)]]
 +
 
== Arrays ==
 
== Arrays ==
 
<syntaxhighlight lang="swift">
 
<syntaxhighlight lang="swift">

Version vom 21. Dezember 2022, 15:29 Uhr

Links

Swift (Programmiersprache)

Arrays

var symbols = ["apple","coin","cherry"]
var symbolIndex = [0,1,2]
var backgrounds = [Color.white,Color.green,Color.red]
backgrounds[0] = Color.white
backgrounds[1] = Color.white
// NOTE: We can use a map function on each element of the array instead:
backgrounds = self.backgrounds.map({ _ in Color.white})

// random values
self.symbolIndex = self.symbolIndex.map({
  _ in Int.random(in: 0...self.symbols.count-1)
})

Multidimensionale Arrays

https://stackoverflow.com/questions/25127700/two-dimensional-array-in-swift

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.