Yogesh Chauhan's Blog

How to create an empty array in Swift?

in Swift on March 7, 2020

We can create an empty array by specifying the Element type of your array in the declaration.

For example:


var numbers: [Double] = []

var names: [String] = []

// The full type name is also allowed
var emptyFloats: Array<Float> = Array()

Add value to the array:


names.append("James")

Also, we can just append a variable. For example,


let myName = "Yogesh"
names.append(myName)

Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf:) method.


names.append(contentsOf: ["Shakia", "William"])

You can add new elements in the middle of an array by using the insert(_:at:) method for single elements and by using insert(contentsOf:at:) to insert multiple elements from another collection or array literal. The elements at that index and later indices are shifted back to make room.


names.insert("Liam", at: 3)

To remove elements from an array, use the remove(at:), removeSubrange(_:), and removeLast() methods.


names.remove(at: 0)

names.removeLast()

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
At-rules: @error and @warn in SCSSSCSSLearn how to use Self JOIN in SQL and MySQLSQL/MySQLWordPress: How to display fields from ACF Flexible Contents?WordPressSome Useful Operators in The SQL WHERE ClauseSQL/MySQLDynamically generate names in SCSS (animation example)SCSSLearn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHPWhat are Stored Procedures for SQL Server?SQL/MySQLHow to use a Subquery to Insert Multiple Rows in SQL Table?SQL/MySQLSimple Page Hit Counter in PHPPHPWhat’s the difference between visibility: hidden and display: none?CSSHow to change CSS with JavaScript?CSSHow to test the WordPress 5.9 Beta 4?WordPress