I keep getting this error in my func
I'm trying to read the value in array answerRecord. I uses a global var arrayCount, which keep track which index im currently pointing to.
func buttonColourControl(){
switch answerRecord[arrayCount]{
case1: xxxxxxx
I did a println in my earlier func and it return a value of int 1 for the var arrayCount
Therefore arrayCount is not empty. So it should be able to interpret the array as:
*assuming arrayCount is now 1
answerRecord[arrayCount] should be interpreted as answerRecord[1]
Please correct me if im wrong
#IBAction func nextButtonClicked(sender: UIButton) {
arrayCount = ++arrayCount
question.text = spouseQuesion[arrayCount]
controlBackNextButton()
answer1Label.text = spouseAnswer1[arrayCount]
answer2Label.text = spouseAnswer2[arrayCount]
answer3Label.text = spouseAnswer3[arrayCount]
println(arrayCount)
buttonColourControl()
}
Let's say you have an array with one object in it:
let arr = ["hello"]
The only valid index into that array is 0. arr[0] is legal. arr[1] is not. The array has 1 element but its index number is 0.
This is true for any array. Every array holds some number of elements. It might be 0 elements, in which case no index is legal. It might be 3 elements, in which case you can refer to the array's elements by index numbers 0, 1, and 2. And so on. That's all. Those are the rules. You cannot use any other index number or you will crash.
So the error message is simply telling you that you are making that mistake. You have an array answerRecord and it has some number of elements - I have no idea how many, and it doesn't matter. Then you are using the expression answerRecord[arrayCount] and the value of arrayCount is outside the bounds I have just explained. That's all you need to know. The error message tells you the bug in your program. Now you can fix it.
Related
I have an array , when I suffix array and want to select element , I get error: Index out of bounds.
But when I prefix array and select element, It's sucess.
How should I do that I can select after suffix array?
Here is code:
let array = [1,2,3,4,5,6,7,8,9,10]
let suffixArray = array.suffix(5)//[6,7,8,9,10]
let prefixArray = array.prefix(5)//[1,2,3,4,5]
print(suffixArray[2])//Index out of bounds
print(prefixArray[2])//sucess print "3"
The problem you are having is that with .suffix the array does not start with 0. So if you wanted to print the 3rd number in the suffix array, you would have to call print(suffixArray[7].
If you read the description for the return value here. It reads:
A subsequence terminating at the end of the collection with at most maxLength elements.
And if you read the description to subsequence:
A collection representing a contiguous subrange of this collection’s elements. The subsequence shares indices with the original collection.
Full example for playground:
let array = [1,2,3,4,5,6,7,8,9,10]
let suffixArray = array.suffix(5) // [6,7,8,9,10]
let prefixArray = array.prefix(5) // [1,2,3,4,5]
var newSuffixArray: [Int] = []
for i in suffixArray {
newSuffixArray.append(i)
}
print(suffixArray[7]) // 8
print(newSuffixArray[2]) // 8
print(prefixArray[2]) // 3
Both prefix and suffix return an ArraySlice rather than another Array.
Here's an excerpt from the ArraySlice documentation:
Unlike Array and ContiguousArray, the starting index for an
ArraySlice instance isn’t always zero. Slices maintain the same
indices of the larger array for the same elements, so the starting
index of a slice depends on how it was created, letting you perform
index-based operations on either a full array or a slice. Sharing
indices between collections and their subsequences is an important
part of the design of Swift’s collection algorithms.
You can see that by looking into the indices property of prefixArray and suffixArray.
Generally you are encouraged to use methods of accessing elements that collections provide instead of assuming values of indices.
In the following Swift code:
self.numbers[2] = Int.random(in: 0...self.symbols.count-1)
Why do we have to write -1?
I don't understand the code.
When you are using A...B, that range includes B in it. See ...(_:_:) docs. So if you say -
Int.random(in: 0...self.symbols.count-1)
It means range starts at 0 and ends at symbols.count-1 including both.
Say an array has 2 elements, it's count is 2, but valid indices are 0, 1 (2 is not a valid index), so you are just making sure that it is restricted to valid index values.
Other way to write the same would be - A..<B, in this range, B is not included. See ..<(_:_:) docs. Following is same as above.
Int.random(in: 0..<self.symbols.count)
You are using ClosedRange here. It is a range which includes both start and end value of the range. You can also used simple Range, which is open so to say. It only includes start value and not the final value.
Lets take an example.
let a = 1 ... 10 // includes all values from 1 to 10
let b = 1 ..< 10 // includes values from 1 to 9
So, basically what you are writing here,
self.numbers[2] = Int.random(in: 0 ... self.symbols.count - 1)
is equivalent to open range using,
self.numbers[2] = Int.random(in: 0 ..< self.symbols.count)
such that you dont need to add -1 to it.
Int.random can take both ClosedRange and Range, here and here.
Here are your code:
self.numbers[2] = Int.random(in: 0...self.symbols.count-1)
It says: your third item in numbers array will be assigned by the random item of symbols array
But how to get the random item of symbols array? You'll get it by its index.
The indexes of an array starting from 0, so, for the last element of array, its index will be the array length - 1, for example, with [1,2,3], the last element's index will be 2.
Here, you used Closed Range, it will include the last element, so if you don't minus count by one, the last index will be 3 (because array.count will return the length of the array), which is produce out of index error
I know this Swift code is valid:
let index = 0
for index in (1...9) {
print(index) // index changes value from 1 to 9
}
But then if you say
index += index
you get the error
"Cannot assign to value: 'index' is a 'let' constant"
So, if index is a constant why is it ok to use it in the loop where its value will change?
So, if index is a constant why is it ok to use it in the loop where its value will change?
You could think of index as being newly created and initialized each time through the loop, just as a variable declared inside the loop's body would be. It makes sense to use let here because normally you don't change the loop counter inside the loop.
Update: After the edit, the code makes more sense, and pkamb's comment really is more clear: the index that you declare with let index = 0 is a different variable from the index used in the for loop.
I have an array containing dictionaries.
let arr = [["test":1], ["test":2], ["test":3], ["test":4]]
I now need to get the one dictionary that contains the highest value for the key "test" (without iterating through everything). I was thinking about filter(_:) but this will only filter out. map(_:) also does not work as I need to filter and not to map.
There's an example how to get the key with the highest value in a dictionary but this does not work in this case.
let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
Any help is appreciated!
You can use max much like in your example.
let arr = [["test":1], ["test":4], ["test":3], ["test":2]]
print(arr.max { $0["test"]! < $1["test"]! })
This gives the dictionary with the highest value.
Of course the use of ! is bad unless it is guaranteed that each dictionary really has a "text" key.
Also note that using max will still result in the entire array being iterated. You can't avoid that unless your dictionaries are always sorted by the value. Then in that case simply use last instead of max.
In a unit test, I want to assert that a method that has the potential to throw an index out of range error actually throws that error.
I'm trying to use
let array = [1,2,3]
XCTAssertThrowsError(array[3])
Why doesn't this work?
How do I test this?
let array = [1,2,3]
XCTAssertThrowsError(array[3])
Why doesn't this work?
Because referring to an out of bounds index does not throw. It crashes, which is a completely different thing.
How do I test this?
How do you test what? If the question is whether a proposed index is legal for a given array, use indices.contains:
let array = [1,2,3]
let ix = 3
XCTAssert(array.indices.contains(ix), "Index out of bounds")