Contents

About Swift syntax 4 (frequently used functions in Array type)

   Jan 18, 2024     2 min read

About “Swift Syntax 4 (Frequently used functions in Array type)”

I had the opportunity to study iOS this time, so I’ve been studying grammar, and I’d like to write a post to summarize it.

In this article, I will introduce various functions of the Array type that are often used.

First, let’s see how to create an array

Creating an Array

How to create and initialize an array

Example

var numbers: [Int] = [1, 2, 3]

append function

Adds a new element to the end of an array.

Example

numbers.append(4) // numbers: [1, 2, 3, 4]

count function

Returns the number of elements in an array.

Example

let count = numbers.count // count: 4

isEmpty

Checks if an array is empty.

Example

if numbers.isEmpty {
    print("The array is empty")
} else {
    print("The array is not empty")
}
// Output: The array is not empty

insert

Inserts an element at the specified index.

Example

numbers.insert(0, ar: 0) // numbers: [0,1,2,3,4]

remove

Removes the element at the specified index.

Example

numbers.remove(at: 0) // numbers: [1,2,3,4]

subscripting

Use an index to access or modify an element in an array.

Example

let firstNumber = numbers[0] // firstNumber: 1
numbers[2] = 5 // numbers: [1,2,5,4]

contains

Checks if a specific element is in the array.

Example

if numbers.contains(5) {
    print("Contains 5!")
}
// Output: Contains 5!

first and last

Access the first and last elements of an array. Returns ‘nil’ if the array is empty.

Example

let first = numbers.first // first: Optional(1)
let last = numbers.last // last: Optional(4)

map, filter, reduce

Using the paradigm of functional programming, you can transform, filter, accumulate, and more on arrays.

example

let doubled = numbers.map { $0 * 2 } // doubled: [2, 4, 10, 8]
let evenNumbers = numbers.filter { $0 % 2 == 0 } // evenNumbers: [2, 4]
let sum = numbers.reduce(0, +) // sum: 12

Functional programming features

It helps you manage complex expressions, makes your code more reusable and testable, and allows you to write more reliable code, even in multi-threaded environments.