Viktor.w
Viktor.w

Reputation: 2317

Try to return an array in a for loop

I am very new to Solidity, so sorry for the silly question. I am trying to add an element of a struct and then return it, here is my code:

struct Flat {
    uint256 priceInWei;
    address currentOccupant;
    bool flatIsAvailable;
}


Flat[8] public flatDB;

modifier landlordOnly() {
    require(msg.sender == landlordAddress);
    _;
}

constructor() public {
landlordAddress = msg.sender;
for (uint i=0; i<8; i++) {
    flatDB[i].flatIsAvailable = true;
    if (i % 2 == 0) {
        flatDB[i].priceInWei = 0.1 ether;
    } else {
        flatDB[i].priceInWei = 0.2 ether;
    }
  }
}

uint256[] array;
    
function getFlatDB() payable public returns (uint256) {
    
    for (uint i=0; i<8; i++) {
        array.push(flatDB[i].priceInWei);
    }
    return array;
}

But when I try to compile I have an error at line 41:

TypeError: Return argument type uint256[] storage ref is not implicitly convertible to expected type (type of first return variable) uint256. return array; ^---^

Can someone explain me what's wrong? Thanks!

Upvotes: 0

Views: 721

Answers (1)

paradisensei
paradisensei

Reputation: 116

Seems like the return type you have (uint256) doesn't correspond to the type you're actually trying to return (uint256[]). Try rewriting your getFlatDB function in the following way:

function getFlatDB() payable public returns (uint256[]) {
    uint256[] memory array = new uint256[](8);
    for (uint i=0; i<8; i++) {
        array[i] = flatDB[i].priceInWei;
    }
    return array;
}

Note how we declare the temporary fixed size return array inside the function with memory keyword.

Upvotes: 1

Related Questions