Im learning swift and am having a problem Iterating through an array. Here is what I'm trying to do:
func orderStringByOccurence(stringArray: [String]) -> [String: Int]{
var stringDictionary: [String: Int] = [:]
for i in 0...stringArray.count {
if stringDictionary[stringArray[i]] == nil {
stringDictionary[stringArray[i]] = 1
stringDictionary
} else {
stringDictionary[stringArray[i]]! += 1
}
}
return stringDictionary
}
I don't get an error until I try to call this function. Then I get this error:
EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)
I have tried debugging and found that i get the same error when i try this:
for i in 0...arrayFromString.count{
print(arrayFromString[i])
}
So how do I iterate through this array? Thanks for helping out a new
You need to change
for i in 0...arrayFromString.count
to
for i in 0..<arrayFromString.count
As it is now, you iterate through the array and then one past the end.
You can also use a different style of for loop, which is perhaps a little better:
func orderStringByOccurence(stringArray: [String]) -> [String: Int] {
var stringDictionary: [String: Int] = [:]
for string in stringArray {
if stringDictionary[string] == nil {
stringDictionary[string] = 1
} else {
stringDictionary[string]! += 1
}
}
return stringDictionary
}
Also, you can simplify your logic a bit:
for string in stringArray {
stringDictionary[string] = stringDictionary[string] ?? 0 + 1
}
Update - For the sake of completeness, I thought I'd add a reduce example here as well. Note that as of Swift 5.1 return statements in single line functions can be implied (SE-0255).
func orderStringByOccurence(stringArray: [String]) -> [String: Int] {
stringArray.reduce([:]) { result, string in result.merging([string: 1], uniquingKeysWith: +)}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With