Iterate through an array in fast

Im learning fast and i have a problem. Iterate through an array. Here is what I am 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 do not 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 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 go through this array? Thank you for your help in creating the new

+4
source share
3 answers

You need to change

for i in 0...arrayFromString.count

to

for i in 0..<arrayFromString.count

As of now, you iterate over the array, and then one after the other.

You can also use a different for loop style, 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
}

In addition, you can simplify your logic a bit:

for string in stringArray {
    stringDictionary[string] = stringDictionary[string] ?? 0 + 1
}
+10

:

let array = ["1", "2", "3"]

forEach :

array.forEach { item in
    print(item)
}

$0:

array.forEach {
    print($0)
}

, enumerate():

array.enumerate().forEach { itemTuple in
    print("\(itemTuple.element) is at index \(itemTuple.index)")
}
+3

It seems you did not specify. A faster approach would be, in my opinion, not to use an account, but to make a radius based on.

var stringArray = ["1", "2", "3"]
for string in stringArray
{
    print(string)
}
+2
source

Source: https://habr.com/ru/post/1614657/


All Articles