0

I want to fill the dictionary with data, so that it looks like this: 1:Apple 2:Banana 3:Lemon

Sorry, if this is too simple for probably most of you - I am just a beginner. Anyway, here is the code:

var listOfFruit = ["Apple", "Banana","Lemon"]
var key = [1,2,3]
var dictionary = [Int: [String]]()
func createDictionary(){

for index in key {
    dictionary[index] = []
    var listOfFruit = ["Apple", "Banana","Lemon"]
    for index1 in listOfFruit{
        dictionary[index]?.append(index1)
    }
}
}
print(dictionary)

The result of the above is "[:]\n" in my playground.

kangarooChris
  • 718
  • 1
  • 10
  • 21

3 Answers3

2

A functional approach to creating your dictionary could look like this:

let dictionary = zip(listOfFruit, key).map { [$1: $0] }
print(dictionary)
// [[1: "Apple"], [2: "Banana"], [3: "Lemon"]]
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • Hi Michael, thank you for solving this! Can you point me to some documentation about the zip and map items you have in your code. I have no idea what they do or mean. Thanks a lot! – kangarooChris Feb 15 '16 at 19:37
  • Sure: http://swiftdoc.org/v2.1/func/zip/ and https://developer.apple.com/library/prerelease/mac/documentation/Swift/Reference/Swift_CollectionType_Protocol/index.html#//apple_ref/swift/intfm/CollectionType/s:FEsPs14CollectionType3mapurFzFzWx9Generator7Element_qd__GSaqd___ – Michael Kohl Feb 16 '16 at 03:30
0
var listOfFruit = ["Apple", "Banana","Lemon"]
var key = [1,2,3]
var dictionary = [Int: String]()

func createDictionary(){
    for (index, value) in key.enumerate() {
        dictionary[value] = listOfFruit[index]
    }
}

createDictionary()

print(dictionary)
Ahmed Onawale
  • 3,992
  • 1
  • 17
  • 21
0
let listOfFruit = ["Apple", "Banana","Lemon"]
let key = [1,2,3]
var dictionary = [Int: String]()
func createDictionary(){
    var i = 0
    while i < listOfFruit.count {
        dictionary[key[i]] = listOfFruit[i]
        i += 1
    }
}
createDictionary()
print(dictionary)

Note the change of the line:

var dictionary = [Int: [String]]()

to:

var dictionary = [Int: String]()

and the use of the variable i to get the same index from each array.

Shades
  • 5,568
  • 7
  • 30
  • 48
  • Hi Shades, thanks for that. It works, but I have another question. The output created is [2: "Banana", 3: "Lemon", 1: "Apple"], so basically the first line in a dictionary. What I'd need is [1:"Apple"] [2:"Banana"] .... – kangarooChris Feb 15 '16 at 01:06