Change Values while Iterating Over Subarrays in Swift [duplicate] - swift

This question already has answers here:
Swift - How to mutate a struct object when iterating over it
(6 answers)
Closed 9 months ago.
What works in Python doesn't want to work in Swift.
Given is an array with subarrays containing numbers. During iteration, as soon as the condition exists that the element in question contains a certain value at position 0, I want to change the other values in this same subarray.
var coordinatesList = [[0, 1, 1, 1], [1, 12, 17, 23], [2, 81, 29, 66], [3, 41, 20, 94]]
for i in coordinatesList {
if i[0] == 6 {
i[3] = 5
}
}
However, my intention fails, because I get the error message that the element i is a let.
An error message with which I can do nothing at all and do not know how to deal with it.

You can iterate over the indices of the outer array. Then you can read and write the inner arrays using the indices:
for index in coordinatesList.indices {
if coordinatesList[index][0] == 6 {
coordinatesList[index][3] = 5
}
}

Related

Very Basic Misunderstanding of for loops in Swift

I'm new to swift. can someone please explain what I'm doing wrong here.
1.
var numbers = [1, 5, 7, 6, 6, 6, 6, 6, 2]
for i in numbers{
print(numbers[i],terminator: "")
}
why doesn't this just print the numbers in the array?
2.
Here I want to set the elements in the array to a random number from 0 to 2, and then print them.
for j in numbers{
numbers[j] = Int.random(in: 0...2)
print(numbers[j],terminator: "")
}
this seems to work, but then if, outside of the for loop, I print them again:
for k in numbers{
print(numbers[k],terminator: "")
}
It outputs different numbers, from 0 to 2
3.
OK so I try a different syntax:
for m in numbers{
print(m,terminator: "")
}
now I get the same numbers every time and they are not from 0 to 2... I'm sure my mistakes are trivial but an explanation would help me out. Thanks.
to achieve what you expect, you need to loop over the indices of the array, like this:
var numbers = [1, 5, 7, 6, 6, 6, 6, 6, 2]
for i in numbers.indices { // <-- here
print(numbers[i])
}
And as mentioned, read the basics of Swift.

From which direction swift starts to read dictionaries? [duplicate]

This question already has an answer here:
For loop for Dictionary don't follow it's order in Swift [duplicate]
(1 answer)
Closed 5 years ago.
the question that I want to ask, from which directions swift starts to read dictionaries or arrays
when I put some codes like this
let interestingNumber = [
"Square": [1,4,9,16,25],
"Prime": [2,3,5,7,11,13],
"Fiboannci": [1,1,2,3,5,8],
"asd":[2,3,4,5],
"zxc":[3,4,5]
]
for (key,values) in interestingNumber{
print(values)
}
the output is
[1, 4, 9, 16, 25]
[2, 3, 5, 7, 11, 13]
[1, 1, 2, 3, 5, 8]
[3, 4, 5]
[2, 3, 4, 5]
this is not the exact order, so do you know why swift does this ? and it sometimes makes it different too!
I guessed may be it does it in string order, then I tried but I think it is not too, so why swift does do that ?
Just like for NSDictionary, Swift dictionaries are not ordered by key or value. The order will always be unspecified.
If you need the keys to be sorted, your only option is to have an array of ordered keys, and use the for loop over this array.
From apple documentation (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105)
Dictionaries
A dictionary stores associations between keys of the same type and
values of the same type in a collection with no defined ordering. Each
value is associated with a unique key, which acts as an identifier for
that value within the dictionary. Unlike items in an array, items in a
dictionary do not have a specified order. You use a dictionary when
you need to look up values based on their identifier, in much the same
way that a real-world dictionary is used to look up the definition for
a particular word.

Populate a multidimensional array with a loop [duplicate]

This question already has answers here:
Error: "array index out of range" in multidimensional array
(2 answers)
Closed 6 years ago.
I'm trying to populate a multidimensional array with this code:
var array = [[Int]]()
for i in 0...3 {
for j in 0...3{
array[i][j] = i + j <<- Error
}
}
But I get an error:
fatal error: Index out of range
What am I doing wrong?
[[Int]] is not a multidimensional array. It is an array of arrays. That's a very different thing. For example, in an array of arrays, each row may have a different number of columns. It's generally a bad idea to use a nested array as a multidimensional array, particularly a mutable one. It's often incredibly inefficient to modify because it causes a lot of copying every time you change it.
Swift doesn't have a multidimensional array type. If you really need one, you generally have to build it yourself, or redesign to avoid it. If it's small enough, and doesn't change much, it's not that big a deal, but don't let them get large.
That said, the problem is that element [0][0] doesn't exist because you didn't create it. You'd need to initialize the array this way before using it:
var array = Array(repeating: Array(repeating: 0, count: 4), count: 4)
This creates an array of 4 arrays of 4 zeros.
If you want specifically the layout you describe, possibly a better approach is mapping, which is likely going to be more efficient (since it doesn't keep modifying the nested array):
let array = (0...3).map { i in
(0...3).map { j in
return i + j
}
}
Calling array[i][j] is for elements that are already there. You cannot use it to initialize the array, because currently it is just an empty array. You should be using .append instead. Keep in mind that this actually isn't a multi-dimensional array like Rob Napier states, but it accomplishes the same goal in this scenario. Try something like this:
var array = [[Int]]()
for i in 0...3 {
var subArray = [Int]()
for j in 0...3 {
subArray.append(i + j)
}
array.append(subArray)
}
This prints:
[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
Again, may not be the best approach, but this is just how you could do it in Swift.

How to create an array with incremented values in Swift? [duplicate]

This question already has answers here:
Is there a way to instantly generate an array filled with a range of values in Swift?
(4 answers)
Closed 7 years ago.
I know that I can create an array with repeated values in Swift with:
var myArray = [Int](count: 5, repeatedValue: 0)
But is there a way to create an array with incremented values such as [0, 1, 2, 3, 4] other than to do a loop such as
var myArray = [Int]()
for i in 0 ... 4 {
myArray.append(i)
}
I know that code is pretty straightforward, readable, and bulletproof, but it feels like I should be able pass some function in some way to the array as it's created to provided the incremented values. It might not be worth the cost in readability or computationally more efficient, but I'm curious nonetheless.
Use the ... notation / operator:
let arr1 = 0...4
That gets you a Range, which you can easily turn into a "regular" Array:
let arr2 = Array(0...4)

How to add integer to array (with explicite int index) in swift?

I read swift handbook and was trying to do some exercises. But I run into a problem and I do not know if I do something wrong or if xCode 6 beta is just buggy.
// Playground - noun: a place where people can play
import Cocoa
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var lastLargest = Integer[]()
var index = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
//lastLargest[index] = number
index++
largest = number
}
}
}
index
lastLargest
largest
As soon as I uncomment lastLargest[index] = number I do not get any results on right side in playground. Nor I get any infos about index, lastLargest or largest.
Following example does not work either:
var index2 = 0
var lastLargest2 = Integer[]()
lastLargest2[index2] = 1
index2++
lastLargest2[index2] = 2
You are appending using an out of bound array-index. Don't do that. Instead, use append:
lastLargest.append(number)
From Apple's documentation:
You can’t use subscript syntax to append a new item to the end of an array. If you try to use subscript syntax to retrieve or set a value for an index that is outside of an array’s existing bounds, you will trigger a runtime error.
When you're using explicit indexes (subscript notation) to set values in a mutable array, some value must already exist in that array at that index. When you use subscript notation, you're essentially using a 'set', rather than a 'set and add if necessary'.
As a result, you should be using:
lastLargest.insert(number, atIndex: index)
If you want to insert a new item. This will let you insert an item at the specified index, assuming your collection's size is already greater than or equal to the index you're trying to replace.