August 2017 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

31 Aug 2017

Local Notifications using UserNotifications Class - Swift, iOS

8/31/2017 03:00:00 am 0
Local Notifications are mainly used in iOS apps for notifying user when new data or information available for your app.This will notify, even if the app is background.

Earlier we were using UILocalNotification class for sending local notification, now UILocalNotification deprecated in iOS 10.

From iOS 10 apple introduced new class called UserNotifications for sending or receiving notification. We can use UserNotifications for both Local Notification & Remote Notifications.

This Article Covers All Related questions  :

How to schedule a local notification in iOS 10 Swift.
Introduction to User Notifications Framework in iOS 10.
How To Set Up iOS 10 Local Notifications.
How to Make Local Notifications in iOS 10.


Notification center with LOCAL NOTIFICATION


UserNotifications :

UserNotifications framework used for delivery and handling of Local Notification & Remote Notifications. We can use this UserNotifications class for schedule the delivery of local notification based on either time or location. Apps and extensions also use this framework to receive and potentially modify local and remote notifications when they are delivered to the user’s device.

Local Notification :

With this, our app configures the notification details locally and passes those details to the system, which then handles the delivery of the notification when your app is not in the foreground.

When to Use :

Local notification can be used based on app data and functionality. Mostly used because, always apps are not running in foreground so we can alert user when a new information is downloaded from server, or may be from local data.

Local notification and Remote notification both same in appearance, when presented on a given device.

For delivering notification we are having 3 options, we can choose one of the following :

1. An onscreen alert or banner
2. A badge on your app’s icon
3. A sound that accompanies an alert, banner, or badge

Example Project:

First create a new project  open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'LocalNotifications-swift' then tap next and select the folder to save project.

For sending notification we need some action to be done, for that we are adding button to view of ViewController.

Let’s get started by first declaring a property of type UIButton and give auto layouts, title as we requires. Add the following methods to ViewController.swift file:
func addingButton() {
    let sendButton = UIButton()
    view.addSubview(sendButton)
    sendButton.translatesAutoresizingMaskIntoConstraints = false
    sendButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    sendButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    sendButton.widthAnchor.constraint(equalToConstant: 200).isActive = true
    sendButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
    sendButton.setTitle("Send Notification", for: .normal)
    sendButton.setTitleColor(UIColor.white, for: .normal)
    sendButton.backgroundColor = UIColor.blue
    
    sendButton.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
}

@objc func buttonTapped(sender: UIButton) {

}

Call addingButton() inside viewDidLoad() method.

Now Run, we will see Button at center of View looks as :

Notifications Button

RequestAuthorization :

Now , let's dive into notification setup, delivery..

Firstly, we need to configure the app. That means we need to ask the user authentication whether device needs to get notification or not.

To request authorization, call the requestAuthorizationWithOptions:completionHandler: method of the shared UNUserNotificationCenter object.

Replace viewDidLoad() with following method :
override func viewDidLoad() {
    super.viewDidLoad()
    addingButton()
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        if (granted) {
            print("granted")
        }else {
            print(error?.localizedDescription as Any)
        }
    }
}

Build and Run, we will see alert with notification request permissions. Tap 'Allow' for testing, if not then we don't receive any notification.

RequestAuthorization Notifications

Send Notification with Content :

Secondly, we need to send notification, so we are creating UNMutableNotificationContent object for setting up content. Add the following code inside buttonTapped() method :
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Good morning!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Wake up! It's morning time!",
                                                        arguments: nil)
content.sound = UNNotificationSound.default()

So we created UNMutableNotificationContent with title,body and sound. There are more but for us it will be enough.

Next step is trigger, when to trigger there are several trigger methods but we are using UNTimeIntervalNotificationTrigger. Add following line at the end of buttonTapped() method :
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:TimeInterval(10)  , repeats: false)

Here we are giving time interval as 10 sec, that means after tapping button then in next 10 seconds we will get notification.

Then we need request object. Add following line at the end of buttonTapped() method :
let request = UNNotificationRequest(identifier: "MorningAlarm", content: content, trigger: trigger)

Finally, we need to schedule the request using UNUserNotificationCenter object. Add following code at the end of buttonTapped() method :
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
    if let theError = error {
        print(theError.localizedDescription)
    }
}

Build and run, Then tap on notification button and lock the device. After 10 sec we will get Local Notification.

Notification center with LOCAL NOTIFICATION

UNUserNotificationCenterDelegate :

Great we are getting notification, but how to handle after receiving. Good for that we have delegates in place.

so add the following line of code to the end of viewDidLoad() method :
center.delegate = self

There are two delegates methods for handling notifications.

Foreground :

First one userNotificationCenter:willPresentNotification:withCompletionHandler: is for handling when app is running in foreground.

Add the following delegate method :
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print(notification.request.content.title)
    
    // Play a sound.
    completionHandler(UNNotificationPresentationOptions.sound)
}

The completionHandler receives input as UNNotificationPresentationOptions. we used sound option, so when received notification in foreground we get notified with sound.

Background :

Second one userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: is for handling when user taps on notification while app is running in background.

Add the following delegate method :
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    print(response.notification.request.content.title)
    
}

This delegate method will call when user taps on notification.

Inside delegate methods we need to handle our data based on app functionality.

Build and Run the app, Then tap on button then check both cases in Background and Foreground. we will see logs in console.


In next article, we will go through Custom actions on Notifications.

Download sample project with examples :

Read More

29 Aug 2017

Add UIDatePicker as Input View to UITextField Swift - iOS

8/29/2017 10:16:00 am 0
In this article we are going to add UIDatePicker as Keyboard to UITextField and also adding UIToolBar above UIDatePicker.

This Article Covers All Related questions  :

UITextField UIDatePicker inputview Example.
uidatepicker inputview uitextfield.
uidatepicker and inputview swift.
uidatepicker inputview example.
UITextField input with a UIDatePicker.
UIDatePicker pop up after UITextField is Tapped.
Display date picker on UITextField touch.


Read Getting Started with UIDatePicker Tutorial.

Final Output from this article will looks like as follow:

Add UIDatePicker as Input View to UITextField Swift

In this whole project we are not going to use Storyboards. We are adding all views programmatically using autoLayouts.

Add UITextField :

First we are going to add UITextField to the view in ViewController. So declare textField variable before viewDidLoad() as:
var textField = UITextField()

Then add textField to the view by adding following method :
func addTextField() {
    view.addSubview(textField)
    textField.translatesAutoresizingMaskIntoConstraints = false
    textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0).isActive = true
    textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40.0).isActive = true
    textField.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0).isActive = true
    textField.placeholder = "Select date"
    textField.borderStyle = .roundedRect
}

Call addTextField() method inside viewDidLoad() method.

Build and run, we see an textField with an placeholder as 'Select date'.

Add Textfiled Programitically
On tapping textField keyboard will appear from bottom, that's ok. But our target is to get UIDatePicker instead of Keyboard.

No worries, it's easy to achieve.

Add UIDatePicker As Keyboard :

First we need to create UIDatePicker, so declare datePicker object after textField declaration as follow:
var textField = UITextField()
var datePicker = UIDatePicker()

Now initialize and add target to datePicker as follow:
func createDatePicker() {
    datePicker.datePickerMode = .date
    datePicker.addTarget(self, action: #selector(self.datePickerValueChanged(datePicker:)), for: .valueChanged)
}

We set datePickerMode to date only, because we need date only. Then add response method datePickerValueChanged(datePicker:) as follow:
@objc func datePickerValueChanged(datePicker: UIDatePicker) {
    
}

Above method will call every time user scrolls UIDatePicker.

Call createDatePicker() method before addTextField() line inside viewDidLoad() method.

So we created datePicker, but not linked to textField. For that we need to set textField inputView as datePicker. So add the following line at the end of addTextField() method :
textField.inputView = datePicker

Build and run, we see textField, then tap on texfield. Great UIDatePicker is showing up as follow:

TextField With DatePicker

So every time user changes date we should update in textField text. So we need to add following code inside datePickerValueChanged() method :
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none

textField.text = dateFormatter.string(from: datePicker.date)

What we have done here is that, we created dateFormatter with dateStyle as medium and timeStyle as none, because we don't need time.

And finally we are getting Date from datePicker.date, so we are converting Date to string and displaying in textField.

Run the project, we see same as before then select your date it will update in textFiled also.

TextField With DatePicker

Add UIToolBar To UIDatePicker :

Now for adding toolBar over UIDatePicker, we need to first create UIToolBar. so declare toolBar object after datePicker declaration as follow:
var textField = UITextField()
var datePicker = UIDatePicker()
var toolBar = UIToolbar()

Next initialize UIToolBar and add following UIBarButtonItem to toolBar as follow:
func createToolBar() {
    toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 40))
    
    let todayButton = UIBarButtonItem(title: "Today", style: .plain, target: self, action: #selector(todayButtonPressed(sender:)))
    
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonPressed(sender:)))
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width/3, height: 40))
    label.text = "Choose your Date"
    let labelButton = UIBarButtonItem(customView:label)
    
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
    
    toolBar.setItems([todayButton,flexibleSpace,labelButton,flexibleSpace,doneButton], animated: true)
}

What we have done here is that, created four UIBarButtonItem.

todayButton:

Shortcut for selecting today's date. On tapping this button we are calling following method :
@objc func todayButtonPressed(sender: UIBarButtonItem) {
    let dateFormatter = DateFormatter() // 1
    dateFormatter.dateStyle = .medium
    dateFormatter.timeStyle = .none
    
    textField.text = dateFormatter.string(from: Date()) // 2
    
    textField.resignFirstResponder()
}

1. Here again added required dateFormatter, but here we want today's date so simply use Date() property to get current date.

2. Then we are converting to string by using dateFormatter.

3. Dismissing the keyboard(here date picker) using resignFirstResponder() method.

doneButton :

After selecting our date we should dismiss datePicker, this button is for that. On tapping this button we are calling following method :
@objc func doneButtonPressed(sender: UIBarButtonItem) {
    textField.resignFirstResponder()
}

labelButton :

LabelButton is like a placeholder text, we can't add UILabel to UIToolbar so we created custom UIBarButtonItem for adding label.

We can customize that label what ever we like.

flexibleSpace :

FlexibleSpace is for giving equal spaces between items in UIToolBar. FlexibleSpace is also of type UIBarButtonItem.flexibleSpace.

We added all four buttons to toolBar as required order.

Call createToolBar() method before addTextField() line inside viewDidLoad() method.

Good, created toolbar but How to add over datePicker?

Its easy, we are going to set textField inputAccessoryView as toolBar, add following code at the end of addTextField() method:
textField.inputAccessoryView = toolBar

Now Build and run, tap on textfield.

Great we can see UIDatePicker with toolBar on it.

UITextField UIDatePicker inputview Example.

Download sample project with examples :

Read More

28 Aug 2017

Selecting Date and Time with UIDatePicker - iOS, Swift

8/28/2017 09:40:00 am 0

UIDatePicker :

Apple made a ready-made user interface for picking data and time. We can use in our apps using UIDatePicker class.

The date picker is in fact a prepopulated picker view. Example of the date picker control is in the Calendar app, Clock app on the devices.

This Article Covers All Related questions  :

iOS DatePicker tutorial (UIDatePicker) using Swift.
UIDatePicker example in Swift.
Getting Started with the UIDatePicker for iOS Using Swift.
Creating or Making UIDatePicker programmatically.



UIDatePicker image

Example Project :

First create a new project  open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'DatePicker' then tap next and select the folder to save project.

Let’s get started by first declaring a property of type UIDatePicker. Add following line above viewDidLoad() method:
var datePicker = UIDatePicker()

Add datePicker object to the view of our view controller. Add following method:
func adddatePicker() {
    view.addSubview(datePicker)
    datePicker.translatesAutoresizingMaskIntoConstraints = false
    datePicker.heightAnchor.constraint(equalToConstant: 250).isActive = true
    datePicker.leadingAnchor.constraint(equalTo:view.leadingAnchor).isActive = true
    datePicker.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    datePicker.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
}

Call adddatePicker() method inside viewDidLoad() method.

Now let’s Build & run the app and see how it looks

Adding UIDatePicker as Input View to UITextField Swift

We can see that the date picker, by default, has picked today’s date. UIDatePicker supports different modes. We can change mode by using datePickerMode property, of type UIDatePickerMode. Default mode is dateAndTime.

Based on our need,we can set the mode of date picker to any of the values listed in the UIDatePickerMode enumeration.
enum UIDatePickerMode : Int {
    
    case time // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)

    case date // Displays month, day, and year depending on the locale setting (e.g. November | 15 | 2007)

    case dateAndTime // Displays date, hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. Wed Nov 15 | 6 | 53 | PM)

    case countDownTimer // Displays hour and minute (e.g. 1 | 53)
}

Just like UIButton, UIDatePicker sends action messages to its targets whenever the user scrolls date picker. Add following method, like so:
func datePickerChanged(datePicker: UIDatePicker){
    print("date = \(datePicker.date)")
}

To response to these messages, the receiver must add itself as the target of the date picker, add addTarget:action:forControlEvents: method in the end of adddatePicker() method, like so:
datePicker.addTarget(self, action: #selector(datePickerChanged(datePicker:)), for: .valueChanged)

Build and Run, every time the user scroll picker view, we will get message of the selected date from date picker.

The good thing about UIDatePicker is that, we can set maximum date and minimum date limits. So set the minimumDate and maximumDate properties to date picker as by adding following code at the end of adddatePicker() method:
let currentDate = Date()
let oneDay = 24 * 60 * 60
let minDate = currentDate.addingTimeInterval(TimeInterval(-10 * oneDay)) // before 10 days from now
let maxDate = currentDate.addingTimeInterval(TimeInterval(20 * oneDay)) // upto 20 Days from now

datePicker.minimumDate = minDate
datePicker.maximumDate = maxDate

We can then limit the user’s selection on the date to a specific range. In this example code, we limited the user’s input of dates to the range of 10 days to 20 days from now.

Run and try to select the date out of our range, it scrolls back to our limits.


Date picker as a countdown timer, you must set your date picker mode to UIDatePickerModeCountDownTimer and use the countDownDuration property of the date picker to specify the default countdown duration.

Suppose if we want to set default count Down duration to 5 min, then write the following code at the end of adddatePicker() method:
datePicker.datePickerMode = .countDownTimer
let fiveMin = TimeInterval(5 * 60)
datePicker.countDownDuration = fiveMin

Build and run, we can see result as follow :


Download sample project with examples :

Read More

26 Aug 2017

Adding Blur Effects to Views Using UIVisualEffectView - iOS, Swift

8/26/2017 10:50:00 am 1
Adding blur effects to various UI components on your application is easy.

This Article Covers All Related questions  :

Adding blur effect to background in swift.
Creating a blurring overlay view.
UIVisualEffectView Tutorial: Getting Started.
Add blur and vibrancy using UIVisualEffectView.

We can achieve this using following two classes.

UIBlurEffect :

This is a class that represents a blur effect. You can initialize an instance of this class with its designated constructor and pass a value of type UIBlurEffectStyle to it. This value will then decide what type of blur effect you want to create.

UIVisualEffectView :

This is a simple UIView subclass that can accept and apply a visual effect of type UIVisualEffect. Because the UIBlurEffect class is a subclass of the UIVisualEffect, you can simply create a blur effect and pass it to your visual effect view. Once you have the visual effect view, you can add it to any other existing view that you have on or off screen.
Applying a blur effect on a view

Example project:

In this example we are going to add blur effect on imageView.

First create a new project  open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'BlurEffect' then tap next and select the folder to save project.

We are going to add UIImageView on the ViewController.

Open ViewController.swift file, then add following method for adding imageView as subview.
func addImageView() {
    let imageView = UIImageView()
    view.addSubview(imageView)
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.heightAnchor.constraint(equalToConstant: 250).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 250).isActive = true
    imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    imageView.image = UIImage(named:"flower.jpg")
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
}

We added imageView using autoLayouts but not used storyBoards. Call addImageView() method in viewDidLoad().

Download a sample flower image for testing and name it as 'flower.jpg'.

Build and Run, we see an flower image in center of view.

Flower image with blur effect

What we want to do now is add a blurred view on top of this image view. As we learned before in this article, we are going to create our blur effect and then create a visual effect view on top of our current view, like so :
func addBlurView() {
    
    let blurEffect = UIBlurEffect(style: .light) // 1
    
    let blurView = UIVisualEffectView(effect: blurEffect) // 2
    
    view.addSubview(blurView)
    blurView.translatesAutoresizingMaskIntoConstraints = false
    
    blurView.heightAnchor.constraint(equalToConstant: 200).isActive = true
    blurView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    blurView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    blurView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

Call addBlurView() method in viewDidLoad().

The UIBlurEffect class can be initialized with any of the blur styles that are specified in the UIBlurEffectStyle enumeration like so:
enum UIBlurEffectStyle : Int {

    
    case extraLight

    case light

    case dark

    
    @available(iOS 10.0, *)
    case regular // Adapts to user interface style

    @available(iOS 10.0, *)
    case prominent // Adapts to user interface style
}

1. In our example code, we used a light blur effect, but you can use any of the ones just listed.

2. Once you have your blur effect, you can add it to the UIVisualEffectView class. This class itself can accept any visual effect of type UIVisualEffect.

Another class of the aforementioned type  is  the UIVibrancyEffect.  This  class  is  very  similar  to  the UIBlurEffect class,  and  in  fact  under  the  hood  uses  a  blur  effect  as  well. UIVibrancyEffect brings out the colors on the layers that are behind it.


For instance, if you have a  popup  window  that  is  about  to  appear  on  top  of  another  view  that  contains  many colorful photos on it, it is best to add a UIVibrancyEffect to a visual effect view and construct your popup using this visual effect view.


That way, the colors underneath the popup (colors that come from the photos) will be more appealing to the user and the user will be able to get a better understanding of the content under your popup.

Build and Run, Great we see blurEffect on the image.


Download sample project with examples :

Read More

25 Aug 2017

Dynamic type(Text and Image) & Image scaling Uisng Preserve Vector Data iOS11

8/25/2017 10:42:00 am 0
In this article we will discuss several common tips and tricks for supporting Dynamic Type.

Dynamic type means increasing text or images sizes dynamically based on device settings.

Dynamic type(Text and Image) & Image scaling Uisng Preserve Vector Data iOS11


Setting Up :

First create new project with single view and name it as "Dynamic Type".

For testing tap settings -> General -> Accessibility  -> Larger Test inside we can change preferred reading size.

While testing we need to change multiple times, that take too time for testing. No Worries we have alternate tool for testing for that tap on  Xcode -> Open Developer Tool -> Accessibility Inspector.

Accessibility Inspector. Beta

Change device to simulator and tap on settings icon we can see size inspector bottom, change sizes there it will update real time.

Accessibility Inspector. Settings Icon

 There are different techniques for dynamic type. We will go through step by step.

Text style fonts (UIFontTextStyle) :

By using UIFontTextStyle we can easily make UILabel dynamic.

First create UILabel object. Open ViewController.swift and add following line above viewDidLoad() method.
var textLabel = UILabel()

Add textLabel as subview to view. We are adding programmatically as follow.
func addTextLabelAsSubview() {
    view.addSubview(textLabel)
    textLabel.translatesAutoresizingMaskIntoConstraints = false
    textLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0).isActive = true
    textLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0).isActive = true
    textLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 8.0).isActive = true
    
    textLabel.text = "Hello World..!"
} 

We are using autoLayouts but not using storyboards.

Call addTextLabelAsSubview() method inside viewDidLoad().

Build and Run, we see Hello World..!. That's not we are looking for, open accessibility inspector then change size to largest. But nothing changed in simulator.

Accessibility Inspector. Default settings

Accessibility Inspector. Large fonts

No worries for that we need to add adjustsFontForContentSizeCategory property and set to true. It will change font size dynamically.

AdjustsFontForContentSizeCategory :

For this property to take effect, the element’s font must be one of the following:

     - a font vended using +preferredFontForTextStyle: or +preferredFontForTextStyle:compatibleWithTraitCollection: with a valid UIFontTextStyle
     - a font vended using - [UIFontMetrics scaledFontForFont:] or one of its variants


So we are using first one i.e, UIFontTextStyle.

Add following lines to the end of addTextLabelAsSubview() method.
textLabel.adjustsFontForContentSizeCategory = true
textLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1)

Now Build and Run, change size, Bingo! size is changing real time.

Dynamic type change real time

Great, But the end is truncating for largest. So fix that by following technique.

Line wrapping (numberOfLines):

textLabel that appear multi line have numberOfLines set to a value other than the default of 1.

So for us we need dynamic . so simply add set numberOfLines to 0. It will wrap automatically based on size. Add following code at the end of addTextLabelAsSubview() method.
textLabel.numberOfLines = 0

Build and Run, Great now its working perfect.

There are different techniques we will update soon.

Read More

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

Post Top Ad