Arrays in Swift

 Arrays:

In simple words an array is a collection of data of similar type. otherwise Array is an ordered, random-access collection type. Arrays are one of the most commonly used data types in apps. We use the Array type to hold elements of one type, the element type of the array. An array can store elements of any type---from integers to classes.



 Basics of Arrays: 

Creating an Empty Array:

The following three declarations are equivalent:

var arrString: [String] = []
print(arrString)   //[]

var arrString1 = [String]()
print(arrString1)   //[]

var arrString2 = Array<String>()
print(arrString2)   //[] 


Array literals:

An array literal is written with square brackets surrounding comma-separated elements: 

 // Create an immutable array of type [Int] containing 4, 5, and 7
let arrayOfInts = [4, 5, 7]

The compiler can usually infer the type of an array based on the elements in the literal, but explicit type annotations can override the default: 

let arrayOfUInt8s: [UInt8] = [4, 5, 7]   // type annotation on the variable
print(arrayOfUInt8s) //[4, 5, 7]

let arrayOfUInt8s1 = [4, 5, 7] as [UInt8] // type annotation on the initializer expression
print(arrayOfUInt8s1) //[4, 5, 7]

let arrayOfUInt8s2 = [4 as UInt8, 5, 7]
print(arrayOfUInt8s2) //[4, 5, 7] 


Arrays with repeated values:

An immutable array of type [String], containing ["AppCodeZip", "AppCodeZip", "AppCodeZip", "AppCodeZip"]

let arrStrings = Array(repeating: "AppCodeZip",count: 4)
print(arrStrings)   

//["AppCodeZip", "AppCodeZip", "AppCodeZip", "AppCodeZip"] 


Creating arrays from other sequences:


let dictionary = ["id" : 4, "Name" : "AppCodeZip"] as [String : Any]

 // An immutable array of type [(String, Any)], containing [(key: "id", value: 4), (key: "Name", value: "AppCodeZip")]

 let arrayOfKeyValuePairs = Array(dictionary)
print(arrayOfKeyValuePairs)

//[(key: "id", value: 4), (key: "Name", value: "AppCodeZip")]


Sorting an Array of Strings / Integer:

As Array conforms to SequenceType, we can generate a new array of the sorted elements using a built in sort method. 

The most simple way is to use sorted():

let words = ["Hello", "Bonjour", "Salute", "Ahola"]
let sortedWords = words.sorted()
print(sortedWords) // ["Ahola", "Bonjour", "Hello", "Salute"] 

or sort() 

var mutableWords = ["Hello", "Bonjour", "Salute", "Ahola"]
mutableWords.sort()

print(mutableWords)
// ["Ahola", "Bonjour", "Hello", "Salute"]


Sort an array of Integer value:


let a = [4,50,6,7,8,9]
let sort_a = a.sorted(by:>)

print(sort_a) // [50, 9, 8, 7, 6, 4]

You can pass a closure as an argument for sorting:

let names = ["D", "F", "F", "A", "C", "O"]
func backword(s1:String, s2:String) -> Bool{
    return s1 < s2
}
var reverseName = names.sorted(by: backword(s1:s2:))
print(reverseName)      //["A", "C", "D", "F", "F", "O"]


//Closure Expression Syntax
reverseName = names.sorted(by: {(s1:String, s2:String) -> Bool in
    return s1 < s2
})
print(reverseName)      //["A", "C", "D", "F", "F", "O"]

//Inferring Type From Context
reverseName = names.sorted(by: { s1, s2  in return s1 > s2 })
print(reverseName)      //["O", "F", "F", "D", "C", "A"]

//Implicit Returns from Single-Expression Closures

reverseName = names.sorted(by: { s1, s2 in s1 < s2 })
print(reverseName)       //["A", "C", "D", "F", "F", "O"]

//Shorthand Argument Names

reverseName = names.sorted(by: {$0 > $1})
print(reverseName)     //["O", "F", "F", "D", "C", "A"] 

sort on a lowercase version of the elements:

let words = ["Hello", "bonjour", "Salute", "ahola"]
let sortedWords = words.sorted { $0.lowercased() < $1.lowercased() }

print(sortedWords) // ["ahola", "bonjour", "Hello", "Salute"]

To properly sort Strings by the numeric value they contain, use compare with the .numeric option: 

let files = ["File-42.txt", "File-01.txt", "File-5.txt", "File-007.txt", "File-10.txt"]
let sortedFiles = files.sorted() { $0.compare($1, options: .numeric) == .orderedAscending }
print(sortedFiles)
// ["File-01.txt", "File-5.txt", "File-007.txt", "File-10.txt", "File-42.txt"]


Array of Dictionary data sorted in alphabetically:


var dic_Array = [[String:String]]()
dic_Array = [
[
    "name": "Lucy",
    "age": "27"
],
[
    "name": "Kush",
    "age": "26"
],[
    "name": "Maishu",
    "age": "24"
],[
    "name": "John",
    "age": "35"
],[
    "name": "AppCodeZip",
    "age": "30"
]]

 let sortedResults = (dic_Array as NSArray).sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)]) as! [[String:AnyObject]]

print(dic_Array)   //[["name": "Lucy", "age": "27"], ["age": "26", "name": "Kush"], ["name": "Maishu", "age": "24"], ["age": "35", "name": "John"], ["name": "AppCodeZip", "age": "30"]]

print(sortedResults)    //[["name": AppCodeZip, "age": 30], ["age": 35, "name": John], ["name": Kush, "age": 26], ["age": 27, "name": Lucy], ["name": Maishu, "age": 24]]


Filtering an Array:

You can use the filter(_:) method on SequenceType in order to create a new array containing the elements of the sequence that satisfy a given predicate, which can be provided as a closure.

For example, filtering even numbers from an [Int]: 

let numbers = [22, 41, 23, 30]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers)  // [22, 30]

Filtering a [Person], where their age is less than 30: 

struct Person {
    var age : Int
}
let people = [Person(age: 22), Person(age: 41), Person(age: 23), Person(age: 30)]
let peopleYoungerThan30 = people.filter { $0.age < 30 }
print(peopleYoungerThan30) // [Person(age: 22), Person(age: 23)]


Using Filter with Structs:


Frequently you may want to filter structures and other complex data types. Searching an array of structs for entries that contain a particular value is a very common task, and easily achieved in Swift using functional programming features. What's more, the code is extremely succinct.

struct Painter {    enum `Type` { case Impressionist, Expressionist, Surrealist, Abstract, Pop }
var firstName: String
var lastName: String
var type: Type
    }
    let painters = [
        Painter(firstName: "Claude", lastName: "Monet", type: .Impressionist),
        Painter(firstName: "Edgar", lastName: "Degas", type: .Impressionist),
        Painter(firstName: "Egon", lastName: "Schiele", type: .Expressionist),
        Painter(firstName: "George", lastName: "Grosz", type: .Expressionist),
        Painter(firstName: "Mark", lastName: "Rothko", type: .Abstract),
        Painter(firstName: "Jackson", lastName: "Pollock", type: .Abstract),
        Painter(firstName: "Pablo", lastName: "Picasso", type: .Surrealist),
        Painter(firstName: "Andy", lastName: "Warhol", type: .Pop)
    ]

    // list the expressionists
    dump(painters.filter({$0.type == .Expressionist}))
//▿ 2 elements
//▿ __lldb_expr_13.Painter
//  - firstName: "Egon"
//  - lastName: "Schiele"
//  - type: __lldb_expr_13.Painter.Type.Expressionist
//▿ __lldb_expr_13.Painter
//  - firstName: "George"
//  - lastName: "Grosz"
//  - type: __lldb_expr_13.Painter.Type.Expressionist

    // count the expressionists
    dump(painters.filter({$0.type == .Expressionist}).count)
    // prints "2"

    // combine filter and map for more complex operations, for example listing all
    // non-impressionist and non-expressionists by surname
    dump(painters.filter({$0.type != .Impressionist && $0.type != .Expressionist}).map({$0.lastName}).joined(separator: ","))
//"Rothko,Pollock,Picasso,Warhol"


Transforming the elements of an Array with map(_:)

As Array conforms to SequenceType, we can use map(_:) to transform an array of A into an array of B using a closure of type (A) throws -> B.

For example, we could use it to transform an array of Ints into an array of Strings like so:

let numbers = [1, 2, 3, 4, 5]
let words = numbers.map { String($0) }
print(words) // ["1", "2", "3", "4", "5"] 

map(_:) will iterate through the array, applying the given closure to each element. The result of that closure will be used to populate a new array with the transformed elements.

Since String has an initialiser that receives an Int we can also use this clearer syntax:

let words = numbers.map(String.init)
print(words) //["1", "2", "3", "4", "5"]

A map(_:) transform need not change the type of the array for example, it could also be used to multiply an array of Ints .

let numbers = [1, 2, 3, 4, 5]
let numbersTimes = numbers.map {$0 * 2}
print(numbersTimes) // [2, 4, 6, 8, 10]

let b = numbers.map { (a) -> Int in
    return a * 4
}
print(b)  //[4, 8, 12, 16, 20]

let c = numbers.map{$0 * 2}
print(c)   //[2, 4, 6, 8, 10]


Map And Dictionaries:

//Mark:- Dictionary
var dic = [String:String]()
dic["name"] = "AppCodeZip"
dic["phone"] = "96XXXXXX"
dic["email"] = "appcodezip@gmail.com"
dic["web"] = "appcodezip.com"

print(dic)    //["web": "appcodezip.com", "phone": "96XXXXXX", "email": "appcodezip@gmail.com", "name": "AppCodeZip"]

let d_key = dic.map {$0.key}
let d_value = dic.map{$0.value}

print(d_key)  //["web", "phone", "email", "name"]
print(d_value)   //["appcodezip.com", "96XXXXXX", "appcodezip@gmail.com", "AppCodeZip"]

let dic_Updated = dic.map { ($0.uppercased(), $1.capitalized) }
print(dic_Updated)    //[("NAME", "Appcodezip"), ("PHONE", "96Xxxxxx"), ("WEB", "Appcodezip.Com"), ("EMAIL", "Appcodezip@Gmail.Com")]


Map And Custom Types:


struct Person {
    let name: String
    let birthYear: Int?
}

let persons = [
    Person(name: "Walter White", birthYear: 1959),
    Person(name: "Jesse Pinkman", birthYear: 1984),
    Person(name: "Skyler White", birthYear: 1970),
    Person(name: "Saul Goodman", birthYear: nil)
]
 let pNames = persons.map { $0.name }

print(pNames)    //["Walter White", "Jesse Pinkman", "Skyler White", "Saul Goodman"]


Map with Array of Dictionary:


var newReleases = [
    [
        "id": 70111470,
        "title": "Die Hard",
        "boxart": "http://cdn-0.nflximg.com/images/2891/DieHard.jpg",
        "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
        "rating": [4.0],
        "bookmark": []
],[
"id": 654356453,
"title": "Bad Boys",
"boxart": "http://cdn-0.nflximg.com/images/2891/BadBoys.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": []],[
"id": 65432445,
"title": "The Chamber",
"boxart": "http://cdn-0.nflximg.com/images/2891/TheChamber.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [4.0],
"bookmark": []],  [
"id": 654356453,
"title": "Bad Boys",
"boxart": "http://cdn-0.nflximg.com/images/2891/BadBoys.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": []],[
"id": 65432445,
"title": "The Chamber",
"boxart": "http://cdn-0.nflximg.com/images/2891/TheChamber.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [4.0],
"bookmark": []],[
"id": 675465,
"title": "Fracture",
"boxart": "http://cdn-0.nflximg.com/images/2891/Fracture.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": []]
]
var videoAndTitlePairs = [[String: Any]]()
newReleases.map { e in
    videoAndTitlePairs.append(["id":e["id"]as! Int , "title": e["title"] as! String])
}
print(videoAndTitlePairs)
    // [["id": 70111470, "title": "Die Hard"], ["title": "Bad Boys", "id": 654356453], ["id": 65432445, "title": "The Chamber"], ["id": 654356453, "title": "Bad Boys"], ["title": "The Chamber", "id": 65432445], ["id": 675465, "title": "Fracture"]]


Element Traverse:


How to enumerate items in an array?

How to iterate a loop with index and element in Swift?


enumerated()-: Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.


let numbers = [3, 1, 4, 1, 5]
// non-functional
for (index, element) in numbers.enumerated() {
    print(index, element)
}
//0 3
//1 1
//2 4
//3 1
//4 5

// functional
numbers.enumerated().map { (index, element) in
    print((index, element))
}
//(0, 3)
//(1, 1)
//(2, 4)
//(3, 1)
//(4, 5)


Modifying values in an array:

There are multiple ways to append values onto an array

var exampleArray = [1,2,3,4,5]
exampleArray.append(6)
//exampleArray = [1, 2, 3, 4, 5, 6]
var sixOnwards = [7,8,9,10]
exampleArray += sixOnwards
//exampleArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and remove values from an array.

exampleArray.removeAtIndex(3)
//exampleArray = [1, 2, 3, 5, 6, 7, 8, 9, 10]
exampleArray.removeLast()
//exampleArray = [1, 2, 3, 5, 6, 7, 8, 9]
exampleArray.removeFirst()
//exampleArray = [2, 3, 5, 6, 7, 8, 9]

Finding the minimum or maximum element of an Array:

You can use the min() and max() methods to find the minimum or maximum element in a given sequence. For example, with an array of numbers.

let numbers = [2, 6, 1, 25, 13, 7, 9]
let minimumNumber = numbers.min() // Optional(1)
let maximumNumber = numbers.max() // Optional(25)


Thanks for reading!!


Similar solutions you may also like...


Post a Comment

1 Comments

  1. Mostly this type of question is used in iOS interview..

    ReplyDelete