Latest Web Stories

1

Exploring Smartphone Influence on the Brain: Neurological Perspectives

2

Angular vs. React: Which One Should You Choose?

3

Discover Serenity: Your Guide to Mindfulness Apps

4

Discover how smartphone apps can enhance your mindfulness practice: 5 Senses Exercise with Apps

5

Discover How Smartwatches Measure Blood Pressure: Explained Simply

6

13 Exciting Games Launching in April 2024: From Freedom Planet 2 to TopSpin 2K25!

7

Discover the 5 Amazon Big Spring Deals on Tablets from Samsung, Lenovo

8

Big Savings Alert: Amazfit Smart Watches Now on Sale on Amazon!

9

Amazon's Big Spring Sale: Top 6 Anker Souncore Headphones and Earbuds Deals

10

Affordable VR Adventures: The Best Budget VR Headsets

11

Fly in Peace: Discover the Ultimate Noise-Cancelling Headphones for Flying

12

Bringing AI to Life: NVIDIA's Digital Human Technolgies in Healthcare, Gaming, and More

13

Discover Exciting New Games on NVIDIA GeForce NOW!

14

Steam Spring Sale 2024 is here: Explore the 10 Best FPS Games

15

The Future of iPhones: Apple's Bold Step into AI with DarwinAI

16

Discover the Magic of Sonos Soundbar: Transform Your Home Entertainment Experience!

17

Enhance Your Home Fun: 5 Best Sonos Soundbars to Amp Up Your Entertainment!

18

Pinterest Introduces AI-Powered Body Type Ranges for Inclusive Searches

19

Embrace the Next Wave: 35+ AI Tools for Enhanced Productivity in 2024

20

Xbox Gaming Bonanza: Lots of New Games with Xbox Game Pass!

21

Sony Paves the Way for Gaming Evolution with 'Super-Fungible Tokens' Patent

22

Smart Printing Choices: 10 Key Factors to Consider When Buying an HP Printer or Any Printer

23

Projector Picks: Explore the Best Mini Projectors for Big Screen Fun!

24

JavaScript Essentials: Your Quick Start to Web Coding

25

Gaming Laptop Guide 2024: 10 Crucial Checks Before You Buy + Top 5 Picks for you!

26

Gaming Joy Awaits: Explore the Best PS5 Games of 2024

27

Epic Games Special: Dive into Astro Duel 2 for FREE this week. See What’s Coming Next Week!

28

Fitbit Fitness Tracker Guide 2024: Choose Your Perfect Fit

29

Feel the Beat: Exploring Top Over-Ear Headphones

30

Explore the Web Development Strategies in 2024: A Developers Handbook

31

Explore Must-Play Nintendo Switch Games in 2024!

32

Eclipse Ready: CE and ISO Certified Solar Eclipse Glasses for a Safe Sky Spectacle

33

Disney and Pixar’s Inside Out 2 Introduces New Emotions to Riley's World

34

Discover Waze's cool new features for safer and happier drives!

35

Discover the Top Picks: Best Smartwatches for Your Lifestyle

36

Discover the Best Smartphones Trending Now: Your Easy Guide to the Best Picks!

37

Sound Revolution: Discover the Best Bluetooth Speakers of 2024!

38

Discover the 10 Best Productivity Apps to Supercharge Your Daily Tasks

39

Discover,Install and Enjoy: The Best Chrome Extensions for Developers in 2024

40

Crack the Code: Your Guide to Computer Programming Magic in 2024

41

Boost Your Content Creation: 10 ChatGPT Prompts to Supercharge Content Creation Productivity

42

10 Best Tech Companies in Silicon Valley

43

Top 10 Web Development Interview Questions you can...

44

Learn how to Answer Tell me about Yourself

45

5 Books You Need to Read Right Now

46

25 Practical Ways to Earn Money Online

Translate this page in your preferred language:


Swift Array

Article by: Manish Methani

Last Updated: October 12, 2021 at 10:04am IST
6 min 2 sec read

The array is used to store elements of the same type. Arrays in swift include strict checking which means Mutable means you can add, and modify the elements of an array whereas in the case of Immutable arrays you cannot.

Note:-

If an array is assigned to a variable then that array becomes Mutable and If an array is assigned to a "constant" then that array becomes Immutable. Create immutable array

let array = NSArray(array: ["First","Second","Third"])
          or
let array1 = ["First","Second","Third"]

Create mutable array

var array2 = ["First","Second","Third"]

Append object to array
array.append("Forth")

Syntax to create an empty array:-

var arrayName = [Type]()

Example :-
var ageArray = [Int]()

Syntax to create an array with repeating elements:-

var arrayname = [Type](repeating:InitialValue ,  count: NumbeOfElements)

/* Create an array with repeated Value say 23 */
var ageArray = [Int](repeating:23 , count:4 )

1) NumbeOfElements:- number of elements you want into an array.

2) InitialValue:- indicates the values of an array. Suppose you give it the value "10". Then all the elements of an array should have the value "10".

Create an array with different elements of same type:-

var arrayName : [type] = [1,2,3,4]
/* Create an array with Different values */
var ageArray:[Int] = [12,23,34]

Examples of different ways to create an array in Swift:-

 /* Create an empty array */ 
var ageArray = [Int]()

/* Create an array with repeated Value say 23 */
var ageArray = [Int](repeating:23 , count:4 )

/* Create an array with different values */
var ageArray:[Int] = [12,23,34]

How to access an array?

To access an array in swift, you can use a subscript index. The index starts with 0 in swift.

var variableName = arrayName[index]

Example:-

import UIKit

var agesArray:[Int] = [12,23,34]

print("Values at first index (agesArray[1])" )

Insert & remove the property of an array

insert property is used to insert an element at a specific index and remove property is used to remove an element at a specific index. but make sure the array should not go out of size.

import UIKit

var ageArray = [Int]( )

ageArray.insert(4, at: 0)
ageArray.insert(5, at: 1)

print("After using insert property array count is (ageArray.count)")

ageArray.remove(at: 0)
print("After using remove property array count is (ageArray.count)")

Output:-

After using insert property array count is 2
After using remove property array count is 1

How to modify an array?

You can use the append() method or addition assignment operator (+=) to add a new item at the end of an array. Be careful with syntax of declaring an array.

Example:-

import UIKit

var agesArray = [Int]()

agesArray.append(20)
agesArray += [40]
agesArray.append(60)

print("Value at first index (agesArray[0])")

Output:-

Value at first index 20

Iterating Over an Array

for-in loop is used to iterate over an array. Swift 3.0 also provides an enumerated() function to iterate over an array and in return, it returns an index of an item.

//: Playground - noun: a place where people can play

import UIKit

var stringArray = [String]()

stringArray.append("Codzify")
stringArray.append("Amazon")
stringArray += ["Google"]

for item in stringArray {
    print(item)
}

Output:-

Codzify
Amazon
Google

Enumerating an Array

Swift 3.0 also provides an enumerated() function to iterate over an array and in return, it returns an index of an item.

//: Playground - noun: a place where people can play

import UIKit

var stringArray = [String]()

stringArray.append("Codzify")
stringArray.append("Amazon")
stringArray += ["Google"]

for (index, item) in stringArray.enumerated() {
    print("Value at index = (index) is (item)")
}

Output:-

Value at index = 0 is Codzify
Value at index = 1 is Amazon
Value at index = 2 is Google

Creating an array by adding two arrays together

With the help of the + operator, you can add two arrays together which as a result forms a new array. But remember both arrays should be of the same type.

//: Playground - noun: a place where people can play

import UIKit

var string1Array = [String]()

string1Array.append("Codzify")
string1Array.append("Amazon")
string1Array += ["Google"]



var string2Array = [String]()

string2Array.append("Manish")
string2Array.append("Jez")
string2Array += ["Larry"]



var string3Array = string1Array + string2Array

for item in string3Array
{
  print(item)
}

Output:-

Codzify
Amazon
Google
Manish
Jez
Larry

Count Property & isEmpty Property of an array

count property is used to count the number of elements in an array. isEmpty property is used to check whether an array is empty or not.

//: Playground - noun: a place where people can play

import UIKit

var ageArray = [Int](repeating:23 , count:4 )
print("Age array count is (ageArray.count)")


var nameArray = [String]()
if(nameArray.isEmpty)
{
 print("Name array is empty")
}
else
{
 print("Name array is not Empty")
}

Output:-

Age array count is 4
Name array is empty

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App