iOS Revisited: Collection Types

Hot

Post Top Ad

Showing posts with label Collection Types. Show all posts
Showing posts with label Collection Types. Show all posts

23 Aug 2017

Dictionaries[iOS] in swift 4. How to Use Dictionaries in Swift 4.0

8/23/2017 06:09:00 am 0
Dictionary is one of the important collection type. We use dictionaries in most of apps for storing and organizing data.

Dictionary is an unordered collection of key-value pairs. Its also called as hashes or associated arrays in  other languages. 

Dictionaries flow chart image in ios - swift 4
 

Syntax :

[Key: Value] // key must be unique of same type

Example :

var blogDict = [
    "name"  : "iOS Revisited",
    "id" : "111",
    "url": "http://iosrevisited.blogspot.com",
    "description": "A blog about ios tutorials."
]

Each element is associated with a unique key. We can access elements from dictionary fast using unique keys.

Creating/Initializing Dictionary :

As arrays we can create empty dictionaries using initializers.

Syntax :

var someDict = [someKey: someValue]()

Example :

var responseMessages = [Int: String]()

// or

var responseMessages: [Int: String] = [:]

// responseMessages is an empty dictionaties of type [Int: String]

The keys are of Int type and values are of String type for responseMessages Dictionary.

Storing objects in Dictionary :

For storing values in dictionary we use subscripts as arrays.

Example :

responseMessages[400] = "Bad request" // stored value as string
responseMessages[403] = "Access forbidden"

Now responseMessages contains two objects with key 400 and 403.

Accessing and Modifying a Dictionary :

You access and modify a dictionary through its methods and properties, or by using subscript syntax.

As with an array, you find out the number of items in a Dictionary by checking its read-only count property.
print("The responseMessages dictionary contains \(responseMessages.count) items.")
// Prints "The responseMessages dictionary contains 2 items."

For checking whether dictionary is empty or not, we can use count = 0 or use the Boolean isEmpty property as a shortcut.
if responseMessages.isEmpty {
    print("The responseMessages dictionary is empty.")
} else {
    print("The responseMessages dictionary is not empty.")
}
// Prints "The responseMessages dictionary is not empty."

Here again adding two more element to responseMessages Dict.
responseMessages[500] = "Internal server error"
responseMessages[200] = "Success"
// the responseMessages dictionary now contains 4 items

For updating or modifying a value we can use subscripts as follows:
responseMessages[500] = "Something went wrong.."
// the value for "500" has been changed to "Something went wrong.."

As an alternative to subscripting for updating or modifying a value we have inbuilt functions updateValue(_:forKey:) to set or update the value for a particular key.

The updateValue(_:forKey:) method returns an optional value of the dictionary’s value type. For a dictionary that stores String values, for example, the method returns a value of type String?, or “optional String”. This optional value contains the old value for that key if one existed before the update, or nil if no value existed:
if let oldValue = responseMessages.updateValue("Access granted", forKey: 403) {
    print("The old value for 403 was \(oldValue).")
}
// Prints "The old value for 403 was Access forbidden."

Removing/Deleting object from Dictionary :

For deleting key-value pair from dictionary we can use subscripts by assigning to nil.
// "Access granted" is not the real response for 403, so delete it
responseMessages[403] = nil
// 403 has now been removed from the dictionary

Alternatively, remove a key-value pair from a dictionary with the removeValue(forKey:) method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:
if let removedValue = responseMessages.removeValue(forKey: 500) {
    print("The removed responseMessage name is \(removedValue).")
} else {
    print("The responseMessages dictionary does not contain a value for 500.")
}
// Prints "The removed responseMessage name is Internal server error"

Iterating Over a Dictionary :

As like arrays, we can iterate over the key-value pairs in a dictionary with a for-in loop.

Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:
for (responseCode, message) in responseMessages {
    print("\(responseCode): \(message)")
}
// 400: Bad request
// 200: Success

You can also retrieve an iterable collection of a dictionary’s keys or values by accessing its keys and values properties:
for responseCode in responseMessages.keys {
    print("response code: \(responseCode)")
}
// response code: 400
// response code: 200

for message in responseMessages.values {
    print("message: \(message)")
}
// message: Bad request
// message: Success

Convert to Arrays :

If you need to use a dictionary’s keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:
let responseCodes = [Int](responseMessages.keys)
// [400, 200]
let messages = [String](responseMessages.values)
// [Bad request, Success]

Swift’s Dictionary type does not have a defined ordering. To iterate over the keys or values of a dictionary in a specific order, use the sorted() method on its keys or values property.
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