Skip to content

Commit 9d4ffd8

Browse files
authored
[Term Entry] Swift Arrays: capacity #6969 (#6991)
* create term entry Capacity * add more ditails to the entry * Remove extra strings * Remove extra edits (in term-entry-template.md) * minor content fixes * fixed format ---------
1 parent 02c082d commit 9d4ffd8

File tree

1 file changed

+55
-0
lines changed
  • content/swift/concepts/arrays/terms/capacity

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
---
2+
Title: 'Capacity'
3+
Description: 'Returns the total number of elements that the array can contain without allocating new storage.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'IOS'
7+
- 'Mobile Development'
8+
Tags:
9+
- 'Arrays'
10+
- 'Collections'
11+
- 'Data Structures'
12+
- 'Memory'
13+
- 'Swift'
14+
- 'Variables'
15+
CatalogContent:
16+
- 'learn-swift'
17+
- 'paths/build-ios-apps-with-swiftui'
18+
---
19+
20+
The **`capacity`** of a Swift [array](https://www.codecademy.com/resources/docs/swift/arrays) represents the amount of memory currently allocated to store elements without requiring a resize. If the number of elements exceeds this capacity, the array automatically reallocates memory, usually following an exponential growth pattern—to ensure efficient performance during appends.
21+
22+
## Syntax
23+
24+
```pseudo
25+
array.capacity
26+
```
27+
28+
**Parameters:**
29+
30+
`capacity` is a read-only property and does not take any parameters.
31+
32+
**Return value:**
33+
34+
Returns the number of elements the array can store in its currently allocated memory without reallocating.
35+
36+
## Example
37+
38+
The following code prints the array's initial capacity, appends elements, and then prints the updated capacity to show how Swift manages memory allocation dynamically:
39+
40+
```swift
41+
var numbers: [Int] = []
42+
print(numbers.capacity)
43+
44+
numbers.append(1)
45+
numbers.append(2)
46+
numbers.append(3)
47+
print(numbers.capacity)
48+
```
49+
50+
The output of this code will be:
51+
52+
```shell
53+
0
54+
3
55+
```

0 commit comments

Comments
 (0)