1
var tempsArray = [65,62,63,64,67,68,69,68,67,65,63,65,65]

func createCoordinates(temps: [Int]) -> Dictionary<Int, Int> {
    var tempCoordinates = [Int: Int]()

    for temperature in temps {
        tempCoordinates[temperature] = temps[temperature]
    }

    return tempCoordinates
}

createCoordinates(tempsArray)

The goal is a function that takes an array of Ints as its only parameter and returns a dictionary of coordinates. In this case the goal is (0:65,1:62,2:63,...)

My code is not executing and is giving me an error of "Array index out of range"

1
  • 1
    You know that a dictionary keyed by an integer from 0..n is effectively an array right? Commented Nov 28, 2015 at 20:22

2 Answers 2

3

This is easy to achieve with enumerate():

let tempsArray = [65,62,63,64,67,68,69,68,67,65,63,65,65]

var dict = [Int:Int]()
for (index, value) in tempsArray.enumerate() {
    dict[index] = value
}

print(dict)

Result:

[12: 65, 10: 63, 5: 68, 7: 68, 0: 65, 11: 65, 3: 64, 2: 63, 4: 67, 9: 65, 6: 69, 8: 67, 1: 62]

Remember that dictionaries are unordered collections.

I believe it will be easy for you to adapt this simple example to your needs. If not, tell me where you're stuck and I'll help.

Sign up to request clarification or add additional context in comments.

2 Comments

I solved this issue almost immediately after posting it with a pretty similar approach to yours. I'm having trouble implementing the sort method on my dictionary and trying to rely on the swift language reference but it might as well be written in Mandarin.
After revising my code, I've solved my own issue, thank you for your support!
0

More simple form:

tempsArray.reduce([Int:Int]()) {
    (var d, v)->[Int:Int] in
    d[d.count] = v
    return d
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.