iOS Revisited

Hot

Post Top Ad

11 Nov 2017

UITapGestureRecognizer - Single Tap & Double Tap Example in Swift 4

11/11/2017 12:41:00 am 0
The iOS UITapGestureRecognizer class has a built-in way to detect taps on any view. We can set the required taps based on our usage.

UITapGestureRecognizer - Single Tap & Double Tap Example in Swift 4

Other Gestures in iOS:

Swipe Gesture Recognizer - UISwipeGestureRecognizer
Pinch Gesture Recognizer - UIPinchGestureRecognizer

Pan Gesture Recognizer - UIPanGestureRecognizer
Long Press Gesture - UILongPressGestureRecognizer
UIRotationGestureRecognizer - Rotate Image View swift

Single Tap Gesture:

For detecting single tap gesture, here's an example:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTap(gesture:)))
    view.addGestureRecognizer(tapGesture)
}

@objc func singleTap(gesture: UITapGestureRecognizer) {
    print("single tap called")
}


Double Tap Gesture:

For detecting Double tap gesture is similar to above, just we need to set numberOfTapsRequired to 2.

Here's an example:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTap(gesture:)))
    tapGesture.numberOfTapsRequired = 2
    view.addGestureRecognizer(tapGesture)
}

@objc func doubleTap(gesture: UITapGestureRecognizer) {
    print("double tap called")
}

Read More

10 Nov 2017

Add Search Bar in Navigation Bar swift | Customize Search Bar

11/10/2017 03:35:00 am 5
In this article we will learn how to add search controller in navigation bar. Customizing search bar like placeholder text, title text, clear button.

Here we are going to use Large Title Navigation bar.

Adding Search Bar In Navigation Bar:

Add the following code in viewDidLoad() method for adding search bar:

if #available(iOS 11.0, *) {
    navigationController?.navigationBar.prefersLargeTitles = true // Navigation bar large titles
    navigationItem.title = "Contacts"
    navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
    navigationController?.navigationBar.barTintColor = UIColor(displayP3Red: 0/255, green: 150/255, blue: 136/255, alpha: 1.0)
    
    let searchController = UISearchController(searchResultsController: nil) // Search Controller
    navigationItem.hidesSearchBarWhenScrolling = false
    navigationItem.searchController = searchController
}

Adding Search Bar In Navigation Bar:

Customizing Search Bar:

Change Search Bar Placeholder text & color:

Add the following line of code to change placeholder text and color:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "Search contacts", attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange])


Change search bar text color:

Add the following line for chaning the text color of search bar:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]


Change cancel button title & color:

For changing cancel button text & color add the following code:

searchController.searchBar.tintColor = UIColor.white
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Dismiss"


Change clear icon:

Add the following code for changing the clear icon:

searchController.searchBar.setImage(UIImage(named: "delete_icon"), for: UISearchBarIcon.clear, state: .normal)


Change search icon:

Add the following code for changing the search icon:

searchController.searchBar.setImage(UIImage(named: "search_icon"), for: UISearchBarIcon.search, state: .normal)


Change Search Bar background color:

For changing the background color add the following code:

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
    if let backgroundview = textfield.subviews.first {
        backgroundview.backgroundColor = UIColor.white
        backgroundview.layer.cornerRadius = 10
        backgroundview.clipsToBounds = true
    }
}


Read More

9 Nov 2017

Swipe Gesture Recognizer On ImageView swift 4

11/09/2017 04:55:00 am 0
Swipe Gesture Recognizer is the one of the important gesture for the iOS users. It's really easy to implement, here we will show implementation to swipe gesture with an example project.

In this example project we are going to swipe image to left, right, up and down.

Swipe Gesture Recognizer On ImageView swift 4

Other Gestures in iOS:

Single Tap & Double Tap Gesture - UITapGestureRecognizer
Pinch Gesture Recognizer - UIPinchGestureRecognizer
Pan Gesture Recognizer - UIPanGestureRecognizer
Long Press Gesture - UILongPressGestureRecognizer
UIRotationGestureRecognizer - Rotate Image View swift 

Getting Started:

Firstly create new Xcode project and save it with 'SwipeGesture'.

Next open the ViewController.swift file and add the imageView as follow.

Adding ImageView:

First create imageView property as follow:

let imageView = UIImageView()

Next add imageView as sub view and give the auto layout constraints. Add the following code in viewDidLoad() method:

imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "cat")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
view.addSubview(imageView)
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.6).isActive = true
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: 1).isActive = true

Adding Swipe Gesture:

First create an instance to UISwipeGestureRecognizer() as follow:

var swipeGesture  = UISwipeGestureRecognizer()

Next add swipeGesture to the imageView. Add the following code to the end of viewDidLoad() method:

let directions: [UISwipeGestureRecognizerDirection] = [.up, .down, .right, .left]

for direction in directions {
    swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipwView(_:)))
    imageView.addGestureRecognizer(swipeGesture)
    swipeGesture.direction = direction
    imageView.isUserInteractionEnabled = true
    imageView.isMultipleTouchEnabled = true
}

The isUserInteractionEnabled property of the view is set to true. Image views and labels set this property to false by default.

Finally add the action for the swipe gesture in all directions:

@objc func swipwView(_ sender : UISwipeGestureRecognizer){
    UIView.animate(withDuration: 1.0) {
        if sender.direction == .right { // Swipe right action
            
            self.imageView.frame = CGRect(x: self.view.frame.size.width - self.imageView.frame.size.width, y: self.imageView.frame.origin.y , width: self.imageView.frame.size.width, height: self.imageView.frame.size.height)
        }else if sender.direction == .left{ // Swipe left action
            
            self.imageView.frame = CGRect(x: 0, y: self.imageView.frame.origin.y , width: self.imageView.frame.size.width, height: self.imageView.frame.size.height)
            
        }else if sender.direction == .up{ // Swipe up action
            
            self.imageView.frame = CGRect(x: self.view.frame.size.width - self.imageView.frame.size.width, y: 0 , width: self.imageView.frame.size.width, height: self.imageView.frame.size.height)
        }else if sender.direction == .down{ // Swipe down action
            
            self.imageView.frame = CGRect(x: self.view.frame.size.width - self.imageView.frame.size.width, y: self.view.frame.size.height - self.imageView.frame.height , width: self.imageView.frame.size.width, height: self.imageView.frame.size.height)
        }
        self.imageView.layoutIfNeeded()
        self.imageView.setNeedsDisplay()
    }
}

Run the project, we will see an image. swipe and test it works as follow:

swift 4 swipe gesture recognizer example,Swipe back and forth through array of images Swift 4,UISwipeGestureRecognizer,How to recognize swipe in all 4 directions swift 4,Handling Swipe Gestures,Detecting Swipe Gestures in iOS 11 with Swift 4,swift 3 swipe gesture recognizer.
Download sample project with example :

Read More

8 Nov 2017

UILabel Left and Right margin Padding with Round Corners in Swift 4

11/08/2017 09:30:00 am 0
In this article we will learn how to add margins/padding to the label using custom UIEdgeInsets.

UILabel Left and Right margin Padding with Round Corners in Swift 4

In the above image we can clearly see "without padding" and "with padding".

"Without padding" is not looking great, so usually developers prefer labels with padding.


Step 1:

Create new swift file and add the following code:

import UIKit

class SSPaddingLabel: UILabel {
    var padding : UIEdgeInsets
    
    
    // Create a new SSPaddingLabel instance programamtically with the desired insets
    required init(padding: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) {
        self.padding = padding
        super.init(frame: CGRect.zero)
    }
    
    // Create a new SSPaddingLabel instance programamtically with default insets
    override init(frame: CGRect) {
        padding = UIEdgeInsets.zero // set desired insets value according to your needs
        super.init(frame: frame)
    }
    
    // Create a new SSPaddingLabel instance from Storyboard with default insets
    required init?(coder aDecoder: NSCoder) {
        padding = UIEdgeInsets.zero // set desired insets value according to your needs
        super.init(coder: aDecoder)
    }
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
    }
    
    // Override `intrinsicContentSize` property for Auto layout code
    override var intrinsicContentSize: CGSize {
        let superContentSize = super.intrinsicContentSize
        let width = superContentSize.width + padding.left + padding.right
        let heigth = superContentSize.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }
    
    // Override `sizeThatFits(_:)` method for Springs & Struts code
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let width = superSizeThatFits.width + padding.left + padding.right
        let heigth = superSizeThatFits.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }
}


Step 2:

Create label and set content insets as follow:

let label = SSPaddingLabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
label.backgroundColor = UIColor.white
label.padding = UIEdgeInsetsMake(8, 15, 8, 15)
label.text = "Hello Padding!"
label.sizeToFit()
label.layer.cornerRadius = label.frame.height/2
label.layer.masksToBounds = true

Download sample project with example :
Read More

7 Nov 2017

Add drop shadow to UIImageView in Swift - iOS

11/07/2017 08:54:00 am 0
In this article we will learn how to add drop shadow to an Image view.

 Step 1:

Add the following UIImageView extension:

extension UIImageView {
    func dropShadow() {
        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = CGSize(width: -1, height: 1)
        self.layer.shadowRadius = 1
        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = UIScreen.main.scale
    }
}

Step 2:

We can use as follow:

let imageView = UIImageView()
imageView.frame = CGRect(x: view.frame.width/2 - 128, y: view.frame.height/2 - 80, width: 256, height: 160)
imageView.dropShadow()
imageView.image = UIImage(named: "Tiger.png")
imageView.backgroundColor = UIColor.white
view.addSubview(imageView)


Read More

6 Nov 2017

Add Badge Value to UIButton & UIBarButton Swift 4 - iOS

11/06/2017 10:42:00 am 1
Badge is for showing the count, for example for showing the number of unread notifications.
Notification with Badge swift ios

Step 1:

Firstly create new swift file and add a subclass to UIButton as follow:


import UIKit

class SSBadgeButton: UIButton {
    
    var badgeLabel = UILabel()
    
    var badge: String? {
        didSet {
            addBadgeToButon(badge: badge)
        }
    }

    public var badgeBackgroundColor = UIColor.red {
        didSet {
            badgeLabel.backgroundColor = badgeBackgroundColor
        }
    }
    
    public var badgeTextColor = UIColor.white {
        didSet {
            badgeLabel.textColor = badgeTextColor
        }
    }
    
    public var badgeFont = UIFont.systemFont(ofSize: 12.0) {
        didSet {
            badgeLabel.font = badgeFont
        }
    }
    
    public var badgeEdgeInsets: UIEdgeInsets? {
        didSet {
            addBadgeToButon(badge: badge)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addBadgeToButon(badge: nil)
    }
    
    func addBadgeToButon(badge: String?) {
        badgeLabel.text = badge
        badgeLabel.textColor = badgeTextColor
        badgeLabel.backgroundColor = badgeBackgroundColor
        badgeLabel.font = badgeFont
        badgeLabel.sizeToFit()
        badgeLabel.textAlignment = .center
        let badgeSize = badgeLabel.frame.size
        
        let height = max(18, Double(badgeSize.height) + 5.0)
        let width = max(height, Double(badgeSize.width) + 10.0)
        
        var vertical: Double?, horizontal: Double?
        if let badgeInset = self.badgeEdgeInsets {
            vertical = Double(badgeInset.top) - Double(badgeInset.bottom)
            horizontal = Double(badgeInset.left) - Double(badgeInset.right)
            
            let x = (Double(bounds.size.width) - 10 + horizontal!)
            let y = -(Double(badgeSize.height) / 2) - 10 + vertical!
            badgeLabel.frame = CGRect(x: x, y: y, width: width, height: height)
        } else {
            let x = self.frame.width - CGFloat((width / 2.0))
            let y = CGFloat(-(height / 2.0))
            badgeLabel.frame = CGRect(x: x, y: y, width: CGFloat(width), height: CGFloat(height))
        }
        
        badgeLabel.layer.cornerRadius = badgeLabel.frame.height/2
        badgeLabel.layer.masksToBounds = true
        addSubview(badgeLabel)
        badgeLabel.isHidden = badge != nil ? false : true
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.addBadgeToButon(badge: nil)
        fatalError("init(coder:) has not been implemented")
    }
}


Step 2:

Finally open ViewController.swift file then add a button as follow:

To UIButton:

let notificationButton = SSBadgeButton()
notificationButton.frame = CGRect(x: view.frame.width/2 - 22, y: view.frame.height/2 - 22, width: 44, height: 44)
notificationButton.setImage(UIImage(named: "Notification")?.withRenderingMode(.alwaysTemplate), for: .normal)
notificationButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 15)
notificationButton.badge = "4"
view.addSubview(notificationButton)

To UIBarButton:

let notificationButton = SSBadgeButton()
notificationButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
notificationButton.setImage(UIImage(named: "Notification")?.withRenderingMode(.alwaysTemplate), for: .normal)
notificationButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 15)
notificationButton.badge = "4"

self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: notificationButton)

Build and Run we will see output as follow:

Add Badge Value to UIButton Swift 4 - iOS

Download sample project with example :

Read More

5 Nov 2017

Tuples Example Swift 4 - Return Multiple values from Function

11/05/2017 07:21:00 am 0
Tuples looks like same as dictionary which holds specific type of data.

Tuples are mainly used for returning multiple value from a function.

Tuples Syntax:

we can create in two ways as follow:

// first way
let person = ("John", "Sam", "Nina")
print(person.0, person.1, person.2) // output looks like : John Sam Nina

// second way most preffered
let p = (name: "Steve", gender: "Male", age: 25)
print(p.name, p.gender, p.age) // output looks like: Steve Male 25

Usage :

Here we will show how to use tuples with an example:

func getTwoHighestNumbersFromList(numbers: [Int]) -> (Int?, Int?) {
    
    if numbers.isEmpty { // optional checking
        return (nil, nil)
    }else if numbers.count == 1 {
        return (numbers[0], nil)
    }
    
    let sortedList = numbers.sorted { (x, y) -> Bool in
        return x > y
    }
    
    return (sortedList[0], sortedList[1]) // returning tuples
}

let highestNumbers = getTwoHighestNumbersFromList(numbers: [1234, 34, 4, 89, 21, 435, 23])
highestNumbers.0
highestNumbers.1

As you can see, the return value from that function is (Int, Int), which is a tuple. Those elements then get accessed using highestNumbers.0, highestNumbers.1.

Read More

3 Nov 2017

Custom Navigation Bar like Twitter in Swift 4

11/03/2017 10:35:00 am 0
Hello guys, in this article we will show how to create custom navigation bar as below:

First create Xcode project an save it. Then embed view controller into navigation controller.

Then add the following method, and call in viewsDidLoad() method:
func setupNavItems() {
    let titleImageView = UIImageView(image: #imageLiteral(resourceName: "title_icon"))
    titleImageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
    titleImageView.contentMode = .scaleAspectFit
    navigationItem.titleView = titleImageView
    
    let followButton = UIButton(type: .system)
    followButton.setImage(#imageLiteral(resourceName: "follow"), for: .normal)
    followButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: followButton)
    
    let searchButton = UIButton(type: .system)
    searchButton.setImage(#imageLiteral(resourceName: "search"), for: .normal)
    searchButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
    
    let composeButton = UIButton(type: .system)
    composeButton.setImage(#imageLiteral(resourceName: "compose"), for: .normal)
    composeButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
    navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: composeButton),UIBarButtonItem(customView: searchButton)]   
}

iOS 11[Swift 4] Navigation Bar With Large Titles and LargeTitleTextAttributes - Color & Font Customization
Read More

2 Nov 2017

PageView using UICollectionView in iPhone X - Swift,UIPageViewController

11/02/2017 12:08:00 pm 0
In most of the apps you use pageviewcontroller. Here we will show how to create page view easily with collection view.

In this article we are going to add subviews programmatically.

PageView  Using  UICollectionView

Download complete project at the bottom of this article.
First create a new project and name it as you like and save.

Add collection View:

First we need to add collection view. We do this using constraints.

Initially open ViewController.swift, add the following property:

var collectionView : UICollectionView!

Next add the following method:

func addCollectionView() {
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.backgroundColor = UIColor.white
    
    self.view.addSubview(collectionView)
    
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    
    collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
    collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
    collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
    collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
}

In above method we added collection view as subview to the main view using constraints.

Add cellId property as follow:

let cellId = "Cell"

Next add the following lines of code in viewDidLoad() method:

addCollectionView()
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)

Then add the delegates methods as follow:

extension ViewController: UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageNames.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! CustomCollectionViewCell
        cell.backgroundColor = UIColor.red
        return cell
    }
}

Now build and run we see normal collection view as follow:

UICollectionView in Swift

Create Custom Collection Cell:

Create new file and name it as "CustomCollectionViewCell". This must be subclass UICollectionViewCell .

Open CustomCollectionViewCell.swift file and add the following code:

let imageView : UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFill
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.clipsToBounds = true
    return imageView
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    
    addSubview(imageView)
    imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0).isActive = true
    imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0).isActive = true
    imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0).isActive = true
    imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0).isActive = true
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Next replace the following line in viewDidLoad() method:

collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)

With

collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

Then add the following code in addCollectionView() right after the layout creation:

layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0

Add some images to project and add the image names as array:

let imageNames = ["Image1", "Image2", "Image3", "Image4"]

Next add the following delegate method inside extension as follow:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}

Finally add paging enabled to collection view. Add the following line inside addCollectionView() method:

collectionView.isPagingEnabled = true

Now build and run we see page View as follow:

PageView using UICollectionView

Looking good! But page control is missing.....

Adding Page Control:

For adding page control first add property as follow:

let pageControl = UIPageControl()

Next add the following two methods:

func addPageControl() {
    self.view.addSubview(pageControl)
    
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    
    pageControl.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
    pageControl.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
    pageControl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
    pageControl.heightAnchor.constraint(equalToConstant: 50).isActive = true
    
    pageControl.backgroundColor = UIColor.clear
    pageControl.numberOfPages = imageNames.count
    pageControl.currentPage = 0
    pageControl.pageIndicatorTintColor = UIColor.red
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    pageControl.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
}

Call addPageControl() method in viewDidLoad() method after addCollectionView() method:

Now Run the project, finally we see actual page view with page control.

PageView using UICollectionView in Swift - UIPageViewController

Download sample project with example :

Read More

1 Nov 2017

Structures VS Classes in Swift - iOS

11/01/2017 11:00:00 am 9
The difference between structure and class is that structure is a value type where class is a reference type.

We explain each one with a example.

Structures VS Classes in Swift - iOS

Classes:

A class is a blueprint or template for an instance of that class. The term "object" is often used to refer to an instance of a class.

Test following code in playground.

class Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1 // both are having same reference
person2.name = "Nick"

print(person1.name) // Nick
print(person2.name) // Nick

Structures:

Structs are preferable if they are relatively small because copying is way safer than having multiple reference to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multi threaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

Test following code in playground.

struct Person {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let person1 = Person(name: "John", age: 26)
var person2 = person1 // both are having value with different references
person2.name = "Nick"

print(person1.name) // John
print(person2.name) // Nick

Read More

Post Top Ad