# Appending Asset into an array

**URL:** <https://forum.flow.com/t/appending-asset-into-an-array/432>\
**Category:** 🏄🏻‍♀️ Cadence\
**Created:** [July 17, 2020, 3:19pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432 "2020-07-17T15:19:15Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![makoto](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/makoto/32/5_2.png) [@makoto](https://forum.flow.com/u/makoto)\
**Post date:** [July 17, 2020, 3:19pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/1 "2020-07-17T15:19:16Z")

</div>

Hi, I am tweaking NFT tutorial transaction to withdraw [NFT which I minted](http://forum.flow.com/t/mismatched-types-expected-never-got-int/421) and append into an array in the transaction as follows.

```auto
    execute {
        let myCollections:[@NonFungibleToken.NFT] = []
        log("NFT Minted and deposited to Account 2's Collection")
        let firstRound = self.minterRef.mintNFT(nfts: 3, recipient: self.receiverRef)
        for element in firstRound {
            log(element)
            myCollections.append(<- self.collectionRef.withdraw(withdrawID: element))
        }
    }

```

However, I am getting `unexpected token in type: '@' ` at ` let myCollections:[@NonFungibleToken.NFT] = []`.

![Screenshot 2020-07-17 at 16.17.15](https://cdck-file-uploads-us1.s3.dualstack.us-west-2.amazonaws.com/flex022/uploads/flow/original/1X/7986db4a6c1664bc98a078fe92a1c09010c1ea4a.png)

If I take that out, then I get `missing resource annotation: `@`as well as`incorrect transfer operation. expected `\<-``

Any suggestions appreciated.

---

<div class="post-metadata">

**Author:** ![makoto](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/makoto/32/5_2.png) [@makoto](https://forum.flow.com/u/makoto)\
**Post date:** [July 17, 2020, 3:27pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/2 "2020-07-17T15:27:57Z")

</div>

The following seems almost working except that I get `loss of resource`.

```auto
    execute {
        let myCollections:@[NonFungibleToken.NFT] <- []
        log("NFT Minted and deposited to Account 2's Collection")
        let firstRound = self.minterRef.mintNFT(nfts: [], recipient: self.receiverRef)
        for element in firstRound {
            log(element)
            myCollections.append(<- self.collectionRef.withdraw(withdrawID: UInt64(element)))
        }
    }

```

---

<div class="post-metadata">

**Author:** ![makoto](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/makoto/32/5_2.png) [@makoto](https://forum.flow.com/u/makoto)\
**Post date:** [July 17, 2020, 4:33pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/3 "2020-07-17T16:33:53Z")

</div>

It turns out that I cannot iterate array of asset, so decided to change to use `Collection`.

The code has no error but when I run, I get the following error.

```auto
WARN[0048] ERR [feba0b] Execution failed:
unexpectedly found nil while forcing an Optional value 

```

Here is my Mint function (the rest hasn’t changed)

```auto
        pub fun mintNFT(nfts: &Collection, recipient: &AnyResource{NFTReceiver}): [Int] {
            var a = 0
            var ids: [UInt64] = nfts.getIDs()
            var nftLength = ids.length

            var newIds: [Int] = []
            if nftLength == 0 {
                var newNFT <- create NFT(initID: self.idCount)
                recipient.deposit(token: <-newNFT)
                self.idCount = self.idCount + UInt64(1)
                return [Int(self.idCount)]
            }

            while a < nftLength {
                // create a new NFT
                var newNFT <- create NFT(initID: self.idCount)
                // deposit it in the recipient's account using their reference
                recipient.deposit(token: <-newNFT)
                recipient.deposit(token: <-nfts.withdraw(withdrawID: ids[a]))
                // change the id so that each ID is unique
                self.idCount = self.idCount + UInt64(1)
                newIds.append(Int(self.idCount))
                newIds.append(Int(ids[a]))
                a = a + 1
            }
            return newIds
        }

```

And here is the transaction

```auto
import NonFungibleToken from 0x01cf0e2f2f715450

// This transaction allows the Minter account to mint an NFT
// and deposit it into its collection.

transaction {

    // The reference to the collection that will be receiving the NFT
    let receiverRef: &{NonFungibleToken.NFTReceiver}
    // The reference to the Minter resource stored in account storage
    let minterRef: &NonFungibleToken.NFTMinter

    let collectionRef: &NonFungibleToken.Collection
    let myCollections: &NonFungibleToken.Collection
    prepare(acct: AuthAccount) {
        // Get the owner's collection capability and borrow a reference
        self.receiverRef = acct.getCapability(/public/NFTReceiver)!
                               .borrow<&{NonFungibleToken.NFTReceiver}>()!
        
        // Borrow a capability for the NFTMinter in storage
        self.minterRef = acct.borrow<&NonFungibleToken.NFTMinter>(from: /storage/NFTMinter)!
        self.collectionRef = acct.borrow<&NonFungibleToken.Collection>(from: /storage/NFTCollection)!
        let collection <- NonFungibleToken.createEmptyCollection()
        acct.save<@NonFungibleToken.Collection>(<-collection, to: /storage/MyCollection)
        self.myCollections = acct.borrow<&NonFungibleToken.Collection>(from: /storage/MyCollection)!
    }

    execute {
        let firstRound = self.minterRef.mintNFT(nfts: self.myCollections, recipient: self.receiverRef)
        for element in firstRound {
            log(element)
            self.myCollections.deposit(token:<- self.collectionRef.withdraw(withdrawID: UInt64(element)))
        }
        for element in self.myCollections.getIDs() {
            log(element)
            let secondRound = self.minterRef.mintNFT(nfts: self.myCollections, recipient: self.receiverRef)
        }
    }
}

```

The full code is in this commit. I think I am almost here.

- flow playground [https://play.onflow.org/64c90f6a-b324-4ccb-8f6a-0b921029b259](https://play.onflow.org/64c90f6a-b324-4ccb-8f6a-0b921029b259)
- github: [https://github.com/makoto/flow/commit/382d472c3e8f725970f8645c2f486806c6a68394](https://github.com/makoto/flow/commit/382d472c3e8f725970f8645c2f486806c6a68394)

Thanks.

---

<div class="post-metadata">

**Author:** ![flowjosh](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/flowjosh/32/362_2.png) [@flowjosh](https://forum.flow.com/u/flowjosh)\
**Post date:** [July 17, 2020, 5:16pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/4 "2020-07-17T17:16:20Z")

</div>

@makoto  
The error you are getting: `unexpectedly found nil while forcing an Optional value ` comes from when you use the force-unwrap operator to unwrap an optional and it finds `nil`.

Whenever you are trying to borrow a reference, I would always recommend using the nil-coalescing operator instead. This way, you can include an error statement so you know which one is `nil`

So for the first line in the transaction, you would change it to

```auto
self.receiverRef = acct.getCapability(/public/NFTReceiver)!
                               .borrow<&{NonFungibleToken.NFTReceiver}>()
                             ?? panic("Could not borrow receiver reference")

```

Could you try that out? That will let you know which line it is coming from.

---

<div class="post-metadata">

**Author:** ![makoto](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/makoto/32/5_2.png) [@makoto](https://forum.flow.com/u/makoto)\
**Post date:** [July 17, 2020, 7:16pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/5 "2020-07-17T19:16:14Z")

</div>

> [@flowjosh](#):
>
> ```auto
> self.receiverRef = acct.getCapability(/public/NFTReceiver)!
> .borrow<&{NonFungibleToken.NFTReceiver}>()
> ?? panic("Could not borrow receiver reference")
> 
> ```
> 
> C

I get exactly the same error.

I think the error is happening at

```auto
self.myCollections.deposit(token:<- self.collectionRef.withdraw(withdrawID: UInt64(element)))

```

I added `log()` to print out line number and that’s where it throws an error

> **[Try out this Playground project](https://play.flow.com/64c90f6a-b324-4ccb-8f6a-0b921029b259)**
>
> Learn Cadence, a revolutionary new smart contract programming language written for the Flow blockchain.

---

<div class="post-metadata">

**Author:** ![flowjosh](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/flowjosh/32/362_2.png) [@flowjosh](https://forum.flow.com/u/flowjosh)\
**Post date:** [July 17, 2020, 8:17pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/6 "2020-07-17T20:17:54Z")

</div>

@makoto Sorry I wasn’t clear, I meant to say that you should add something like that everywhere you try to borrow a reference. You’re right that this isn’t from that. It is from the withdraw function because you are trying to withdraw `id=2` from `collectionRef` instead of `MyCollections`

---

<div class="post-metadata">

**Author:** ![MaxStarka](https://sea2.discourse-cdn.com/flex022/user_avatar/forum.flow.com/maxstarka/32/56_2.png) [@MaxStarka](https://forum.flow.com/u/MaxStarka)\
**Post date:** [July 17, 2020, 9:07pm UTC](https://forum.flow.com/t/appending-asset-into-an-array/432/7 "2020-07-17T21:07:25Z")

</div>

I’ve changed some code here and there:

- Old **MyCollection** item is being destroyed, when transaction is executed (you probably need to rework this into check if **MyCollection** exists. I didn’t had time to dive into the idea, just made the whole thing functional 😅
- **withdraw** method on Collection now returns Optional NFT resource. This would allow you to work with optional bindings in your transaction code later. You can read more about optional bindings here:  
[https://docs.onflow.org/docs/cadence#optional-binding](https://docs.onflow.org/docs/cadence#optional-binding)

This version shall work now:

> **[Try out this Playground project](https://play.flow.com/091e2c80-a76f-4dde-89dd-e4b54270e998)**
>
> Learn Cadence, a revolutionary new smart contract programming language written for the Flow blockchain.
