1

according to this page it is possible to add an entire dictionary to another http://code.tutsplus.com/tutorials/an-introduction-to-swift-part-1--cms-21389

but running the code gave me compilation error

var dictionary = ["cat": 2,"dog":4,"snake":8]; // mutable dictionary
dictionary["lion"] = 7; // add element to dictionary
dictionary += ["bear":1,"mouse":6]; // add dictionary to dictionary

error :

[string: Int] is not identical to UInt8

is there a right way to do this functionality in swift ? of i should add them 1 by 1 ?

A.Alqadomi
  • 1,529
  • 3
  • 25
  • 33
  • 2
    http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary – johny kumar Dec 04 '14 at 06:43
  • Does this answer your question? [How do you add a Dictionary of items into another Dictionary](https://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary) – Rivera May 07 '20 at 15:43

2 Answers2

6

The page you are referring to is wrong, += is not a valid operator for a dictionary, although it is for arrays. If you'd like to see all the defined += operators, you can write import Swift at the top of your playground and command+click on Swift, then search for +=. This will take you to the file where all of the major Swift types and functions are defined.

The page you linked to also includes some other erroneous information on quick glance in the array section where it says you can do this: array += "four". So, don't trust this page too much. I believe you used to be able to append elements like this to an array in earlier versions of Swift, but it was changed.

The good news is that with Swift you can define your own custom operators! The following is quick implementation that should do what you want.

func +=<U,T>(inout lhs: [U:T], rhs: [U:T]) {
    for (key, value) in rhs {
        lhs[key] = value
    }
}
Jarsen
  • 7,432
  • 6
  • 27
  • 26
3

Almost invariably when swift complains something is not like UInt8, there's a casting error in your code that may not be obvious, especially in a complex expression.

The problem in this case is that the + and += operators are not defined for that data type. A very nifty way to join arrays is described here:

How do you add a Dictionary of items into another Dictionary

Community
  • 1
  • 1
clearlight
  • 12,255
  • 11
  • 57
  • 75