Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate through an array in swift

Tags:

arrays

swift

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

like image 616
user3839756 Avatar asked Nov 05 '15 20:11

user3839756


1 Answers

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: +)}
}
like image 134
Charles A. Avatar answered Oct 08 '22 19:10

Charles A.