SWIFT cheat sheet

I’ve added some swift codes which can be helpful for beginners. You can bookmark this page, as it can be used for quick recall.

Declare variables in swift:

Concatenate strings  in swift

Declare arrays in swift

Find number of elements in array in swift

Tuples in swift

Declare Class in swift

Instantiate class in swift

Declare Struct (or structure) in swift

Inherit Class in swift

Declare  simple method / function without argument and return type:

Declare method / function with argument and return type

For loop

For loop in another form

For loop in array

While loop:

 

 

 

 

How to add UIImageView programmatically in swift

You can add UIImageView programmatically in your iOS application  at run time. You can get the image file from server. To avoid complexity, we will use local image file. First create a new project. Copy and paste any image from your local computer in the project. You can download image from here.

UPDATE: After downloading the image, copy it to your project folder. Best way to do this is open the Project navigator of Xcode (If it is not already opened). Then open the folder where your image is located. Drag and drop the image from Finder to you Project Navigator. When a dialog box appear,  Check “Copy items if needed” to project option.

Before I proceed, let me explain the difference between UIImage and UIImageView.

UIImage: It’s the image that we want to display.

UIImageView: It’s something like frame of the image or placeholder of the image where we’ll set our UIImage or image.

Now open your ViewController.swift file.

There are 2 things to add image to your application programmatically.

1. Add image to your “image view”.

2. Add “image view” in your view.

In viewDidLoad method write the following code to add image to your image view:

Now, let’s add the image view in our main view:

We can also set width and height of the image:

The whole code is:

 

How to add UITextField, UITextView and UILabel programmatically in swift 4.0

In iOS app development, sometime we need to add Textfields, textviews, labels etc programmatically. It gives you control over customizing styles, size and position of them. I’m going to place codes (swift Language) here so that you can get all of them from one place.
Following codes will work in any view controller
UITextField:
TextView:
Label:

 

How to add UIButton programmatically in SWIFT

In iOS app development sometime we’ve to create Buttons programmatically or dynamically. Today, I’ll show you how to do this using SWIFT programming language.

Let’s create a new Single View iOS application in Xcode. Name the project “DynamicButton”. Select swift as programming language.

Now go to ViewController.swift. In ViewDidLoad method we’ll write some codes that will add one button to the screen automatically at run time.

Let’s create a new method createButton and write some codes inside the method that will do the magic:

Explanation:

First we initialize a button object and keep it in button variable.

Then we set title and color of title of it.

In the following line of code, we add position and size of the button.

Add the button to view.

Finally let’s call the createButton in viewDidLoad method.

Now if you run the project (cmd + R) you can see a button created. If you tap on the button, nothing will happen at this moment. To call a method when button is pressed, we can write:

Do not forget to add ‘:’ after action method name (i.e. buttonPressed:). In action parameter of .addTarget, you set the method name that should be called. Now write buttonPressed method.

The buttonPressed: method simply displays an alert view. Now run the project and view result.

iOS Simulator Screen Shot Feb 18, 2015, 3.20.49 PM

The whole ViewController.swift will look like this:

 

Still feeling tired? Click here to download the project.

 

 

How to use Core-Data with SWIFT

Core data is a framework that is used to save data in iOS app development and OS X platform. Today we’ll develop an application using SWIFT programming language that will have a textfield, a button and a textview that will save and display data fetched from Core Data. To learn more about Core-Data please visit:

Introduction to Core Data Programming Guide

Summary:

Step 1: Create Project

Step 2: Design Core-Data database

Step 3: Write script to save and fetch data from core data.

 

Step 1:

1. Create a new project in Xcode. In first window of the wizard select Single view application. In next screen, select SWIFT from dropdown box and also check “Use Core Data” checkbox (bottom of the wizard). Please use “NotePad” as your project name.

Screen Shot 2015-02-12 at 11.56.09 PM

2. Open Main.storyboard and add a textfield, a button. Below the button add big textview. ( Note: textfield is for one line. For multiple lines use textview).

Screen Shot 2015-02-13 at 12.06.29 AM

 

Step 2:

1. Now, open NotePad.xcdatamodeld (YourProjectName.xcdatamodeld). This is the place where you design your database.

2. Here you add Entity (Entity is similar to Table of Oracle / MySql database, but not exactly). At the bottom of the page, you will see Add Entity button (1). Click on it. New entity (2) will be added. By double clicking on it, you can change it’s name. I changed it to “Note”

3. Now select the entity (if it’s not already selected). Add “Attribute” to it by clicking + button (3) below the Attributes section. Attribute is similar to column of a table. For each attribute we should select a type from dropdown box. I’m using only one attribute “paper” with type “String”.

4. At this point you have to do an important thing. In Utilities panel (Right side bar), you will see a box labeled: “Class” (4) in entity section. Write here : NotePad.Note; Actually, it should be ApplicationName.EntityName

5. Now we’ll generate Entity Classes. To do this, go to Editor > Create NSManagedObjectSubclass. Select the data model (It’s the file name that we have worked on). In next screen, select Entity name. We’ve only one Entity. Click next. Now, you will see a dialog box for saving entity file. Here, from language dropdown box select swift and finally click Create button.

coredata

Step 3:

1. Add outlets to textField and textview.

2. Add IBAction to button. You can also rename the button to “Add”

3. Open ViewController.swift.

We’ll edit this file. Before we proceed, let me give you an example. Suppose we have some food, one tray and a refrigerator. To save the food, we’ve to put it on the tray and keep the tray inside refrigerator. Saving method of Core data is similar. Here data is food, managedObject is tray and managedObject.save is equivalent to keeping tray contained food inside refrigerator.

Screen Shot 2015-02-16 at 9.45.25 PM

 

First import CoreData in your viewController

declare an array NSManagedObject below IBOutlet declaration. so the code will look like this:

 

To fetch data from CoreData we can use following method:

Above method fetches all data in Note entity. At the end of the method, we used for loop to get each text inside paper and add them in a local variable. finally show all texts in large text view.

To save data in Core data use following code. We are saving text in paper attribute (column) of Note entity (table)

 

Now implement saveNote in IBAction actionAddNote. Clear the text field so that you can add new note.

 

Full source code of ViewController.swift. You can also download the whole project from the link provided at the end this tutorial.

 

You can download the whole project by clicking here.

Parsing JSON object by SWIFT

Today we’ll see how to work with JSON in swift language. We’ll develop a simple currency converter. It will convert USD to Euro by using web API that returns JSON data. Here is the basic structure that we are going to do:
Screen Shot 2014-12-21 at 9.01.36 PM
Let’s begin.
1. Create a new project “CurrencyConverter” and select swift as programming language. Select Single View from next dialog box.

2. Open Main.storyboard and add a textfield, a button and a label. See screenshot for guide. We’ll keep everything simple.

3. Open both Main.storyboard and ViewController.swfit in Assistant editor.

a. Create an IBOutlet for textField and name it txtAmount

b. create an IBOutlet of the label (result) and name it labelResult.

c. Create an IBAction for the button and give it name: actionConvert.


4. Open ViewController.swift in standard editor.

We’ll declare 3 functions (or methods) that will do the following things:

a. getData()
It will get data from server.

b. parseJSON()

This function will convert data received from server into JSON object.

c. displayData()
This function will display the JSON data in UILabel. Call this method inside parseJSON method.

Finally in actionConvert method (or function), call getData and parseJSON.

Run the application to see the result.

 

IMPORTANT NOTE: If you want to fetch JSON Array instead of JSON Object (One JSON array contains one or more JSON objects), please use the following method: