Cadence 1.0 Improvements & New Features
π« New featuresβ
Cadence 1.0 was released in October of 2024. This page provides a historical reference of changes.
View Functions added (FLIP 1056)
π‘ Motivationβ
View functions enable developers to enhance the reliability and safety of their programs, facilitating a clearer understanding of the impacts of their own code and that of others.
Developers can mark their functions as view, which disallows the function from performing state changes. That also makes the intent of functions clear to other programmers, as it allows them to distinguish between functions that change state and ones that do not.
βΉοΈ Descriptionβ
Cadence has added support for annotating functions with the view keyword, which enforces that no mutating operations occur inside the body of the function. The view keyword is placed before the fun keyword in a function declaration or function expression.
If a function has no view annotation, it is considered non-view, and users should encounter no difference in behavior in these functions from what they are used to.
If a function does have a view annotation, then the following mutating operations are not allowed:
- Writing to, modifying, or destroying any resources
- Writing to or modifying any references
- Assigning to or modifying any variables that cannot be determined to have been created locally inside of the viewfunction in question. In particular, this means that captured and global variables cannot be written in these functions
- Calling a non-viewfunction
This feature was proposed in FLIP 1056. To learn more, please consult the FLIP and documentation.
π Adoptionβ
You can adopt view functions by adding the view modifier to all functions that do not perform mutating operations.
β¨ Exampleβ
Before:
The function getCount of a hypothetical NFT collection returns the number of NFTs in the collection.
_17access(all)_17resource Collection {_17_17  access(all)_17  var ownedNFTs: @{UInt64: NonFungibleToken.NFT}_17_17  init () {_17    self.ownedNFTs <- {}_17  }_17_17  access(all)_17  fun getCount(): Int {_17    returnself.ownedNFTs.length_17  }_17_17  /* ... rest of implementation ... */_17}
After:
The function getCount does not perform any state changes, it only reads the length of the collection and returns it. Therefore it can be marked as view.
_10    access(all)_10    view fun getCount(): Int {_10//  ^^^^ addedreturnself.ownedNFTs.length_10    }