11

I am trying to create a smart contract using Solidity 0.4.4.

I was wondering if there is a way to set a mapping with some values already entered to an empty one?

For example:

This initailises a new mappping

mapping (uint => uint) map;

Here I add some values

map[0] = 1;

map[1] = 2;

How can I set the map back to empty without iterating through all the keys?

I have tried delete but my contract does not compile

antonis
  • 123
  • 1
  • 1
  • 9

2 Answers2

11

Unfortunately, you can't. See the Solidity documentation for details on the reasons why. Your only option is to iterate through the keys.

If you don't know your set of keys ahead of time, you'll have to keep the keys in a separate array inside your contract.

Adam Kipnis
  • 10,175
  • 10
  • 35
  • 48
8

I believe there is another way to handle this problem.

If you define your mapping with a second key, you can increment that key to essentially reset your mapping.

For example, if you wanted to your mapping to reset every year, you could define it like this:

uint256 private _year = 2021;
mapping(uint256 => mapping(address => uint256)) private _yearlyBalances;

Adding and retrieving values works just like normal, with an extra key:

_yearlyBalances[_year][0x9101910191019101919] = 1;
_yearlyBalances[_year][0x8101810181018101818] = 2;

When it's time to reset everything, you just call

_year += 1
BananaNeil
  • 10,322
  • 7
  • 46
  • 66