Arrays help you keep many items together in one place. Type inference means Swift can guess what kind of items are inside the array without you saying it out loud.
0
0
Array creation and type inference in Swift
Introduction
When you want to store a list of your favorite fruits.
When you need to keep track of scores in a game.
When you want to group several names together.
When you want to create an empty list and add items later.
When you want Swift to automatically know the type of items in your list.
Syntax
Swift
var arrayName = [item1, item2, item3] // or var arrayName: [Type] = [item1, item2, item3] // or var emptyArray = [Type]()
You can let Swift guess the type by just writing the items inside square brackets.
If you want an empty array, you must tell Swift what type it will hold.
Examples
Swift guesses this is an array of strings because the items are words.
Swift
var fruits = ["Apple", "Banana", "Cherry"]
Here, we tell Swift this array holds integers explicitly.
Swift
var numbers: [Int] = [1, 2, 3, 4]
This creates an empty array that will hold decimal numbers later.
Swift
var emptyDoubles = [Double]()
Swift does not allow arrays with mixed types like strings and numbers together.
Swift
// var mixedArray = ["Hello", 5] // This will cause an errorSample Program
This program shows how to create arrays with and without type inference. It also shows adding items to arrays and printing them.
Swift
import Foundation // Create an array with type inference var colors = ["Red", "Green", "Blue"] print("Colors array before adding:", colors) // Add a new color colors.append("Yellow") print("Colors array after adding:", colors) // Create an empty array of integers var scores = [Int]() print("Scores array initially empty:", scores) // Add scores scores.append(10) scores.append(20) print("Scores array after adding:", scores)
OutputSuccess
Important Notes
Type inference helps write less code and keeps it clean.
Arrays must hold items of the same type; mixing types causes errors.
Creating an empty array requires specifying the type so Swift knows what to expect.
Summary
Arrays store lists of items together.
Swift can guess the type of items in an array if you provide items when creating it.
Empty arrays need a type declared so Swift knows what kind of items will go inside.