iOS Revisited: Arrays

Hot

Post Top Ad

Showing posts with label Arrays. Show all posts
Showing posts with label Arrays. Show all posts

16 Oct 2017

Concatenate/Merge Two Arrays into One Array in Swift 4

10/16/2017 08:46:00 am 0
Append two arrays into a new array with Swift standard library's.

There are 5 different ways for merging arrays in swift. We may choose one of the five following ways according to your needs and requirements.

Sorting Arrays in Swift

Concatenate/Merge Two Arrays into One Array in Swift 4

1. +(_:_:) generic operator:

The following piece of code shows how to merge two arrays of type [Int] into a new array using +(_:_:) generic operator:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let finalArray = arr1 + arr2
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'


2. append(contentsOf:):

The following piece of code shows how to append two arrays of type [Int] into a new array using append(contentsOf:) method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
arr1.append(contentsOf: arr2)
print(arr1)
// output will be '[1, 2, 3, 4, 5, 6]'


3. flatMap(_:):

The following piece of code shows how to concatenate two arrays of type [Int] into a new array using flatMap(_:) method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let finalArray = [arr1, arr2].flatMap({ (element: [Int]) -> [Int] in
    return element
})
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'

4. joined():

Swift provides a joined() method for all types that conform to Sequence protocol (including Array).

So, following piece of code shows how to join two arrays of type [Int] into a new array using Sequence's joined() method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let flattenCollection = [arr1, arr2].joined()
let finalArray = Array(flattenCollection)
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'

5. reduce(_:_:):

The following piece of code shows how to merge two arrays of type [Int] into a new array using reduce(_:_:) method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let finalArray = [arr1, arr2].reduce([], { (result: [Int], element: [Int]) -> [Int] in
    return result + element
})
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'

Use any one of above methods based on your requirement.

Read More

14 Oct 2017

Sorting Arrays in Swift 4 - iOS 11

10/14/2017 10:10:00 am 0
Sorting Arrays using swift 4 is a simple using sorted() built-in method.

Sorting Arrays in Swift 4 - iOS 11

Here is a example for sorting an simple array containing string objects.
let friends = ["Sophia", "James", "Olivia", "Mike", "Nina"]
print(friends.sorted())

//output is '["James", "Mike", "Nina", "Olivia", "Sophia"]'

We can sort complex arrays also easily using same built-in method sorted().

Creating an array with custom struct:

struct friendStruct {
    var name: String
    var age: Int
}

let array = [
    friendStruct(name: "Sophia", age: 23),
    friendStruct(name: "Olivia", age: 25),
    friendStruct(name: "James", age: 21),
    friendStruct(name: "Nina", age: 26),
    friendStruct(name: "Mike", age: 23)
]

Sort by name:

let sortedArray = array.sorted { (firstStruct, secondStruct) -> Bool in
    if firstStruct.name < secondStruct.name {
        return true
    }
    return false
}

Sort by age:

let sortedArray = array.sorted { (firstStruct, secondStruct) -> Bool in
    if firstStruct.age < secondStruct.age {
        return true
    }
    return false
}


We can sort Date also like above.

5 Ways To Concatenate/Merge Two Arrays into One Array in Swift 4
Read More

16 Aug 2017

Arrays or Lists Tutorial With Examples in iOS using Swift 4 - Collection Types

8/16/2017 03:53:00 am 0
We mostly use Arrays and Dictionaries while developing apps. Sets also we will use but not as much as Arrays and Dictionaries.

In this tutorial we dive into Arrays using Swift 4. We are going to use Playgrounds for learning Arrays.


Array Tutoria In Swift, Objective c Ios


Arrays:

An Array is a list of ordered values of the same type. Array may contain same value at different indexes.

5 Ways To Concatenate/Merge Two Arrays into One Array in Swift 4
 

Initialization :

In swift arrays initialization like below. Copy and paste in Playground.
var userIds = Array()
print("userIds is of type [Int] with \(userIds.count) items.")
Output: userIds is of type [Int] with 0 items.

'userIds' is an Empty Array of type Int.  

     How to Create Empty Array ?

      We can create empty array using following line.
var emptyArray = [Any]()
       Any may be Int, Float, Double, String etc...

 

Adding/Inserting elements to Array :


In swift for adding elements to Array we use Append().
userIds.append(1)

userIds.append(3)

print(userIds)
Output: [1, 3]

userIds now contains 2 value of type Int

For getting the elements count from Array use 'count'.

print(userIds.count)
Great. By using Append element is adding to array at end. If we want to add at a particular index append won't work.

No worries it's easy.

Now for adding at starting we using 'insert'.

userIds.insert(20, at: 0)

print(userIds)
Output: [20, 1, 3]

We can add any element at any index between 0 to userIds.count.

Adding at second position follows as below.

userIds.insert(45, at: 1)

print(userIds)
Output: [20, 45, 1, 3]

Note: Index starts from 0. second position means index = 1.

Make userIds Array empty. So simply write following code.

userIds = []

print(userIds)
Output: [20, 45, 1, 3]

Array With Default Values:

create simple array with default values.

var defaultArray = [2, 4, 6, 8]
For adding same element multiple times swift made easy function.
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

Creating an Array By Adding Two Arrays Together:

In swift we can create an array by adding two compatable arrays using an additional operator (+).

The new created array type is inferred from type of two arrays you add together.

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
 
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
There are more we can do with Arrays. We will cover later.

Modifying & Accessing Arrays:

Subscripts :

We can modify or access arrays using Subscripts.
var whishList = ["juice", "biscuits", "fruits", "vegetables"] // Create array with string literals
Suppose we want to access first element simply we can use subscript as follow.
var firstItem = whishList[0]
To modify a element in an array we can use subscripts.

Modify second item with 'chocolates' as follow.

whishList[1] = "chocolates"

// the second item in the list is now equal to "chocolates" rather than "biscuits" var firstItem = whishList[0]

Using Array Methods And Properties :

We use array method to remove object from an array.
whishList.removeFirst()

// the first item in the array has just been removed
// whishList now contains 3 items, and no juice
We can remove from a specific index also.
whishList.remove(at: 1)

// the item at index 1 has just been removed
// now whishList contains only 2 item
We can insert an elemnt to an array as follow.
whishList.insert("milk", at: 0)

// whishList now contains 3 items
// "milk" is now the first item in the list

Iterate/Loop Over an Array :

We can get all values from an array by simply iterating over it using for-in loop.
for item in whishList {
    print(item)
}

// milk
// fruits
// vegetables
We can use old method also with index but not efficient.

For getting index we use a different method called enumerated(). Iterate using this method we will get both index and value. It's a great features and efficient for getting two things for single execution.

for (index, value) in whishList.enumerated() {
    print("item\(index+1): \(value)")
}

// Item 1: milk
// Item 2: fruits
// Item 3: vegetables

Summary:

What we learnt from this article.

1. An array is a collection of elements of same type in a sequential order.
2. Elements order won't change by itself.
3. Initializing an array using different methods.
4. Adding elements to an array using append() function.
5. Inserting an element using insert(at:) function.
6. Adding two array using additional operator (+) will give an New Array.
7. We can modify and access array items using subscripts.
8. In array index starts from 0.
9. Deleting or Removing item from array using Remove(at:) function.
10. Iterating over an array using for-in loops
.

Read More

Collection Types in Swift 4 - Arrays, Dictionaries, Sets.

8/16/2017 03:49:00 am 0
In iOS Collection Types are used for storing data based on required data structure. Mainly there are three types.


1. Arrays
2. Dictionaries
3. Sets



Collection Types in Swift 4, Swift 3 , Objective - C,iOS




Arrays:

Array is an collection of objects in a sequential order. Array is the most important data structure for storing objects.

The objects are in sequential order and the key for accessing these objects is their index, an integer specifying a value’s position in the sequence. Index starts from 0 to n-1. Where n is number of objects in an array.

Objects may be Int, Double, String etc..

Example:

var animals = ["Lion", "Tiger", "Elephant"] // Array with Strings As Objects

var userIds = [12, 16, 22] // Array with Ints As Objects


Array, NSArray, NSMutableArray, Lists in Swift 4, Swift 3, Objective - C, iOS


For more examples and detailed explanation on Arrays.

Dictionaries:

Dictionary is unordered collection of objects with a key value pair.

For accessing an object we use keys. Dictionaries also allow for fast insertion and deletion operations.

For example we create dictionary for elephant.

Example:

var dict = [
    "name"  : "Elephant",
    "color" : "Black",
    "gender": "Male",
    "Weight": "5500 Kgs"
]


Dictionaries, NSDictionary, NSMutableDictionary HashMaps in Swift 4, Swift 3, Objective - C, iOS

For more examples and detailed explanation on Dictionaries .

Sets:

Set is an unordered collection of unique elements. Sets are like same as Arrays. When we don't need any order and ensure that each element appears only once in a collection.

The main advantage of sets is that we can perform so many operation that array doesn't. We can perform union, intersection of array using sets.

Example:

var animals: Set = ["Lion", "Tiger", "Elephant"] // same as array but 'Set' type


Sets, Union, Intersection in Swift 4, Swift 3, Objective - C, iOS

Read More

Post Top Ad