• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

ios

NSUnknownKeyException – this class is not key value coding-compliant for the key

November 6, 2019 By Ravi Shankar Leave a Comment

NSUnknownKeyException – this class is not key value coding-compliant for the key common error that most of the Swift beginners would face during the learning period.

Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[<Handbook.StudentEntryController 0x78f948a0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key nametxt.’
*** First throw call stack:
(
0 CoreFoundation 0x02316a14 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x01751e02 objc_exception_throw + 50
2 CoreFoundation 0x02316631 -[NSException raise] + 17
3 Foundation 0x013e71bc -[NSObject(NSKeyValueCoding) setValue:forUndefinedKey:] + 282
4 Foundation 0x0134183a _NSSetUsingKeyValueSetter + 115
5 Foundation 0x013417bf -[NSObject(NSKeyValueCoding) setValue:forKey:] + 295
6 UIKit 0x02cac06d -[UIViewController setValue:forKey:] + 85
7 Foundation 0x0137601d -[NSObject(NSKeyValueCoding) setValue:forKeyPath:] + 384
8 UIKit 0x02f1fcb4 -[UIRuntimeOutletConnection connect] + 132
9 libobjc.A.dylib 0x0176600c -[NSObject performSelector:] + 62
10 CoreFoundation 0x02246f51 -[NSArray makeObjectsPerformSelector:] + 273
11 UIKit 0x02f1e34e -[UINib instantiateWithOwner:options:] + 2102
12 UIKit 0x02cb3abc -[UIViewController _loadViewFromNibNamed:bundle:] + 429
13 UIKit 0x02cb44f4 -[UIViewController loadView] + 189
14 UIKit 0x02f47b66 -[UITableViewController loadView] + 88
15 UIKit 0x02cb4900 -[UIViewController loadViewIfRequired] + 154
16 UIKit 0x02cbb406 -[UIViewController __viewWillAppear:] + 114
17 UIKit 0x02cde5b9 -[UIViewController(UIContainerViewControllerProtectedMethods) beginAppearanceTransition:animated:] + 202
18 UIKit 0x02cf09cc -[UINavigationController _startCustomTransition:] + 1389
19 UIKit 0x02d02769 -[UINavigationController _startDeferredTransitionIfNeeded:] + 803
20 UIKit 0x02d03ada -[UINavigationController __viewWillLayoutSubviews] + 68
21 UIKit 0x02edfc4a -[UILayoutContainerView layoutSubviews] + 252
22 UIKit 0x02bb5008 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 810
23 libobjc.A.dylib 0x01766059 -[NSObject performSelector:withObject:] + 70
24 QuartzCore 0x029b480a -[CALayer layoutSublayers] + 144
25 QuartzCore 0x029a84ee _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 388
26 QuartzCore 0x029a8352 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
27 QuartzCore 0x0299ae8b _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 317
28 QuartzCore 0x029cee03 _ZN2CA11Transaction6commitEv + 561
29 QuartzCore 0x029d0674 _ZN2CA11Transaction17flush_transactionEv + 50
30 UIKit 0x02ae28bc _UIApplicationHandleEventQueue + 8398
31 CoreFoundation 0x022306ff __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
32 CoreFoundation 0x0222638b __CFRunLoopDoSources0 + 523
33 CoreFoundation 0x022257a8 __CFRunLoopRun + 1032
34 CoreFoundation 0x022250e6 CFRunLoopRunSpecific + 470
35 CoreFoundation 0x02224efb CFRunLoopRunInMode + 123
36 GraphicsServices 0x05cf5664 GSEventRunModal + 192
37 GraphicsServices 0x05cf54a1 GSEventRun + 104
38 UIKit 0x02ae8bfa UIApplicationMain + 160
39 Handbook 0x0007513d main + 93
40 libdyld.dylib 0x04b11a21 start + 1
41 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

This issue occurs when a storyboard refers to a deleted or renamed IBOutlet. If you navigate to the connection instepctor of the ViewController, you shoud notice an exclaimation mark as shown below.

Remove the IBOutlet mapping by clicking on X mark and remove the orphaned IBOutlet.

Filed Under: IBOutlet, ios, NSUknownKeyException

Swift – WebView demo

November 6, 2019 By Ravi Shankar 24 Comments

Updated for Swift 5

In this short tutorial, we will see an example in Swift programming language using UIWebView. The WebView will load a webpage and provide option to refresh, stop, go back and go forward. This tutorial should give a brief overview on how to declare IBAction, IBOutlets and use Objective-C classes (NSURL and NSURLRequest) in Swift


Interface Design

Step 1: Create a Single View Application Project and make sure to select the programming language as Swift

Choose Swift Language in Xcode

Step 2: Select Main.Storyboard under Project navigator. then drag and drop WebView and Toolbar from Object Library to the View Controller.

Step 3: Now place four bar button items on Toolbar to provide stop, refresh, go back and go forward functionality. You can also use flexible and fixed separators for aligning the bar button items.

Use Suggested Constraints in Xcode 6

Step 4: Make sure to use the SuggestedConstraints for WebView and Toolbar. You can do this by selecting the controls and using the Reset to Suggested Constraints available as part of Resolve Auto Layout option. This would ensure that the controls gets adjusted automatically depending upon the device’s screen width and height.

Reset to Suggested Constraints

Updated – 28/08/2014

Since some users are facing problems with Reset to Suggested Constraints in Xcode 6 Beta 6, you can use Pin option to define the four constraints using the default values. Then click Add 4 Constraints available at the bottom of the screen.

201408281213.jpg

Write Code

Step 5: Navigate to ViewController.swift file on the Project Navigator. Add the following line after class ViewController: UIViewController which defines the IBOutlet element for WebView.

@IBOutlet var webView: UIWebView!

Then connect this IBOutlet element to the WebView on InterfaceBuilder.

Step 6: In the viewDidLoad function, create URL and NSURLRequest for the webpage and associate this with the WebView by calling loadRequest method.

override func viewDidLoad() 
{   
  super.viewDidLoad() 
  let url = NSURL(string: "https://rshankar.com")
  let request = NSURLRequest(url: url! as URL)       
  webView.delegate = self
  activityIndicator.hidesWhenStopped = true
  activityIndicator.startAnimating()
  webView.loadRequest(request as URLRequest) 
}

Step 7: Now add the corresponding IBAction methods for the four buttons stop, refresh, go back and go forward. And connect these IBActions to the buttons on Interface builder.

func webViewDidFinishLoad(_ webView: UIWebView) 
{ 
      activityIndicator.stopAnimating()   
}                                                                                           

@IBAction func doRefresh(_: AnyObject) {                                                              
  webView.reload()
}

@IBAction func goBack(_: AnyObject) 
{   
   webView.goBack()    
}

@IBAction func goForward(_: AnyObject) {
  webView.goForward()
}

@IBAction func stop(_: AnyObject) 
{
   webView.stopLoading()
}

Step 8: Compile and run the project by selecting a suitable simulator.

Download the souce code from GitHub.

Filed Under: ios, Programming, Xcode Tagged With: Swift, WebView, Xcode

Value for SWIFT_VERSION cannot be empty.

November 6, 2019 By Ravi Shankar Leave a Comment

This error occurs when the Swift version is not specified under Swift Compiler Languge for your project.
All you need to do is, Navigate to Build Settings -> Swift Compiler Language, from the drop down specify the Swift version.

Filed Under: ios, Swift Compiler, Swift Version

Journey with Swift

October 29, 2017 By Ravi Shankar

This is about my journey as a Swift developer and some of the points discussed here could be useful to anyone who want to re-invent themselves as a software developer or if they want start a career as a Software developer.

Past experience

I have been working in Software industry for years in wide range of technologies. Like many I felt the need for a change and wanted to switch over to the latest technologies. I was interested in iOS app development though I started with Objective-C within a year switched to Swift.

Be an early adopter

Choosing the technology matters and if you are one of the early adopter then you get new opportunities quickly. Being one of the early adapter of Swift helped me a lot to get noticed quickly. Also if the technology has the backing of some big corporates then you will grow with the technology.

Blog a learning tool

I started writing simple tutorials in Swift and shared this with the wider audience through my blog. This helped me to articulate the concepts well and also get valuable feedback from readers. In the later stage I got many opportunities/leads through my blog. Check out Ash Furrow and Kristina Thai talks on the benefiting of writing a blog.

Stay focussed

After picking up iOS/Swift, I got distracted time and again with Android and other hybrid platforms. But remember the process of learning any technology is the same and you are not going to achieve your goal by focussing on different platforms at the same time. Stay focussed to reach your goal quickly.

Build a portfolio

Another way of building confidence is to publish apps under your name. You can start with simple apps and increase the features as you gain more and more experience. I sometimes felt embarrased with the choice of initial apps that I made and the code that I wrote. It is quite natural to feel that way as long you keep learning continuously

Eat Swift, Sleep Swift, Breathe Swift

Don’t put all your eggs in one basket. I was working as a Objective-C developer but quit the job to focus only on Swift. There were not many gigs available during the first year hence become an iOS mentor. The best way to keep learning is by teaching others. This allowed me to spend all my time in learning and practising Swift.

Networking and team events

Join local meet-ups learn from other like minded people. If possible attend conferences where you get a chance to meet some international speakers as well. Participate in Hackathons and test your ability in new technologies by conceptualising the app idea in to MVP in the short period of time.

Take up new opportunities

I got a lead through my blog for reviewing a Swift book and also to co-author a Udemy course. Don’t hesitate to take up new opportunities as long as it aligns with your technology. This can alway add up to your portfolio and online presence.

Hard work, dedication!

After many unsuccessful bidding finally I got a small prototype work in Swift. The client again awarded me a full fledged project which later become a full-time work. Even if it is a small gig, hard work and dedication definitely pays off.

 

I want to end with one quote this is especially for the people in their 30s & 40s. You can become or re-invent yourself as software developer at any age. “Age is no barrier. It’s a limitation you put on your mind”. Don’t compare yourself with other developers know your strength and work around your limitations. Happy Coding!!

Filed Under: ios, iOS Developer, Software Developer, Swift

My first iOS developer conference – try! Swift Tokyo 2017

October 28, 2017 By Ravi Shankar 2 Comments

Attending conference is one way of keeping yourself up to date with the latest trends in any industry. This is true for every software developer as well. After re-skilling myself and picking up iOS development I wanted to attend some good conferences but not many were happening in India. Heard a lot about try! Swift from Alvin and Giridharan and registered for try! Swift Tokyo.

Conference

I needed a visa to travel to Japan and the organisers were quick to help me out. Thanks to Katsumi and Natasha for the paper work, the level of commitment shown to sort this out gave me a glimpse of what to expect in the conference.

I had arrived a day earlier and was able to attend the Tokyo Skytree tour followed by a reception at Pivotal labs arranged for all the international attendees. This was like an ice breaker and I got introduced to few of the attendees and speakers as well.

The conference was for 2 days + 1 day for workshops and hackathon. Each session was scheduled for 25 minutes followed by office hours with the speaker where you get a chance to clarify your queries and have detailed discussion with some renowned speakers. They had also scheduled lighning talks with duration of 5 minutes each. This was a huge conference with 700+ attendess, great speakers and well organised one as well.

Hackathon and Workshop

After the 2 day conference all the attendees had a chance to participate in hackathon. This gave me a chance to work with some bright Japanese developers. There were also some workshops conducted by Realm, IBM, Build a cross-platform 2D game with Swift by @ewingfighter and React Native workshop by orta

Why should anyone attend?

  • Networking with attendees and speakers, use the office hours after talk to clarify the queries with the speakers.
  • You can participate in the social events after conference. trySwift are the best at this.
  • If you are interested in job opportunities then you have chance to meet companies as many sponsors were doing recruitment as well
  • Get up to speed in new iOS technologies and chance to know about some exciting startups.
  • You can also participate in the local Swift and iOS community events.
  • On a side note you have a chance to explore country and interact with people.

It was worth the money spent and would recommend this for all iOS developer especailly try! Swift conferences.

Now try! Swift has come to India as well !! Register Now

Filed Under: Conference, ios, Networking, Swift, try! Swift

Assertions supported in XCTest

March 23, 2017 By Ravi Shankar Leave a Comment

Here you can find the list of Assertions supported by XCTest and it is essential to know all these assertion if you are practicing Test Driven Development in IOS. You can get this list from XCTestAssertions.h

  • XCTFail(<#format…#>) – This unconditionally fails the test.
  • XCTAssertNil(<#a1#>, <#format…#>) – Failure message when object is not nil.
  • XCTAssertNotNil(<#a1#>, <#format…#>) – Failure message when object is nil
  • XCTAssertEqual(<#a1#>, <#a2#>, <#format…#>) – Failure message when expressions(a1 & a2) are not equal.
  • XCTAssertNotEqual(<#a1#>, <#a2#>, <#format…#>) – Failure message when expressions(a1 & a2) are equal.
  • XCTAssertEqualObjects(<#a1#>, <#a2#>, <#format…#>) – Failure message when objects(a1 & a2) are not equal.
  • XCTAssertNotEqualObjects(<#a1#>, <#a2#>, <#format…#>) – Failure message when objects(a1 & a2) are not equal.
  • XCTAssertEqualWithAccuracy(<#a1#>, <#a2#>, <#accuracy#>, <#format…#>) – Failure message when a1 is not equal to a2 with + or – accuracy.
  • XCTAssertNotEqualWithAccuracy(<#a1#>, <#a2#>, <#accuracy#>, <#format…#>) – Failure message when a1 is equal to a2 with + or – accuracy.
  • XCTAssertNoThrow(<#expression#>, <#format…#>) – Failure message when expression does throw exception.
  • XCTAssertNoThrowSpecific(<#expression#>, <#specificException#>, <#format…#>) – Failure message when expression throws specific exception.
  • XCTAssertNoThrowSpecificNamed(<#expression#>, <#specificException#>, <#exception_name#>, <#format…#>) – Failure message when expression throws specific class with specific name.
  • XCTAssertThrows(<#expression#>, <#format…#>) – Failure message when expression does not throw exception.
  • XCTAssertThrowsSpecific(<#expression#>, <#specificException#>, <#format…#>) – Failure message when expression does not throw specific exception.
  • XCTAssert(<#expression#>, <#format…#>) – Failure message when expression is false.
  • XCTAssertTrue(<#expression#>, <#format…#>) – Failure message when expression is false.
  • XCTAssertFailure(<#expression#>, <#format…#>) – Failure message when expression is true.

Filed Under: Develop, ios, Swift, Xcode Tagged With: Assertions, Xcode, XCTest

UITableView Demo in Swift

March 10, 2016 By Ravi Shankar 2 Comments

In this tutorial, we will see some of the common UITableView operations such as Adding, Updating, Deleting and Moving records using Swift.

Let us start with a TableView placed over a ViewController instead of using UITableViewController. By this way you will learn lot more about the functionality of UITableView. Add a new file and select Cocoa Touch Class as a template for the new file.

In “Choose options for your new file” screen, enter the class name as TableViewDemoController with subclass as UIViewController. Then save the new file under your preferred location.

User Interface

Navigate to Main.stotyboard then drag and drop a ViewController from Object Libray to Storyboard. Select the ViewController and click Show Identity Inspection and enter the class name as “TableViewDemoController”

Drag and drop Table View from object library to the View Controlller and make sure Table View is aligned properly. Now place a Table View Cell from object library on top of the TableView.

Set the identifier for Prototype cell to “CellIdentifier” using Show Identity Inspector.

Now select the tableview in the Document Outline pane and click Connection Inspector under Utilies pane. Connect the dataSource and delegate Outlets to the TableViewDemoController (yellow color circle on top View Controller)

Display Data

In this demo, we will be seeing how to display list of Socia Media icons. Here are the steps to load those icons in TableView.

First create a Struct that would act as a place holder for holding the name and image file name. Right click on the Project, select New File. In template screen, choose Swift file and provide name as SocialMedia and save the file.

Edit SocialMedia.swift and add the following code snippet. Apart name and imageName property, this also has computed property that returms UIImage based upon the image file name.

import UIKit

struct SocialMedia {

    var name:String
    var imageName:String
    var image: UIImage {
        get {
            return UIImage(named: imageName)!
        }
    }

}

Now Drag and drop social icon images from folder to Xcode project (download images from gitHub repoistory). Navigate TableViewDemoController.swift and add the following code snippet.

var data:[SocialMedia] = [SocialMedia]()

//MARK:- Populate data   

    func loadData() -&amp;gt; [SocialMedia] {

        data.append(SocialMedia(name:"Evernote",imageName:"evernote"))
        data.append(SocialMedia(name:"Facebook",imageName:"facebook"))
        data.append(SocialMedia(name:"GitHub",imageName:"github"))
        data.append(SocialMedia(name:"Google",imageName:"google"))
        data.append(SocialMedia(name:"LinkedIn",imageName:"linkedin"))
        data.append(SocialMedia(name:"Paypal",imageName:"paypal"))
        data.append(SocialMedia(name:"Pinterest",imageName:"pinterest"))
        data.append(SocialMedia(name:"Twitter",imageName:"twitter"))
        data.append(SocialMedia(name:"Vimeo",imageName:"vimeo"))
        data.append(SocialMedia(name:"YouTube",imageName:"youtube"))

        return data
    }

We have declared an array called data which will hold all the SocialMedia icon related information. The function loadData is used for adding all the social media images. Now call this function in the viewDidLoad method.

override func viewDidLoad() {
	super.viewDidLoad()
	 // call loaddata
	 loadData()
 }

In order display data, ViewController needs to conform UITableViewDataSource protocol. Add UITableViewDataSource to the class declaration next to UIViewController.

class TableViewDemoController: UIViewController, UITableViewDataSource {

Then implement the following methods in TableViewDemoController class, these required methods when a class conforms to UITableViewDataSource protocol.

extension TableViewDemoController: UITableViewDataSource {

    // MARK:- TabvleView dataSource methods

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&amp;gt; Int {
        return data.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&amp;gt; UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(IDENTIFIER,
            forIndexPath: indexPath)

        let socialMedia = data[indexPath.row]

        cell.textLabel?.text = socialMedia.name

        cell.imageView?.image = socialMedia.image

        return cell
    }
}

Finally we need to create IBOutlet for tableView and connect with tableView control in Storyboard.

@IBOutlet var tableView: UITableView!

Now you should be able to build and run the project. This should show list all Social Media icons as shown below

Customize UITableView

In order the customize the tableview, the TableViewDemoController class needs to conform to UITableViewDelegate protocol. Let us say you want to increase the height of tableview rows. Then implement the function heightForRowAtIndexPath to return the height for each row.

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -&amp;gt; CGFloat {
	return 60.0
}

Build and run the project should show the difference in height.

Add and Update row

Navigate to Main.storyboard and add a new View Controller to Interface builder. This View Controller will be used for capturing name of the icon when adding a new row.

This View Controller has a text field to accept the name of the Social Media icon, Done button to save the entered informatiom and Cancel button to cancel the operation. Make sure to create Unwind segue for Done and Cancel button by Control drag and drop each button to Exit icon on the View Controller. Also provide the identifer for the Unwind segue as addAction and cancelAction.

Navigate to TableViewDemoController and add Bar Button Item to the left hand side. Set the Identifier of Bar Button Item to Add.

Now Control + Drag from the Add button to DetailViewController and select Segue as Push with identifier as “addAction”. Similarly to allow users to edit the existing row, Control + Drag TableView prototype cell to DetailViewController and set identifier for the Push segue as “editAction”.

Add a new Cocoa Touch Class file to the existing project with Sub class as UIViewController and name of the file as DetailViewController. Set this file as the class name in the Identity Inspector of DetailViewController in Interface builder.

Update the DetailViewController.swift and replace the existing code with the following lines of code.

import UIKit

class DetailViewController: UIViewController {

    var socialMedia: SocialMedia?

    @IBOutlet var textFeild:UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let name = socialMedia?.name {
            textFeild?.text = name
        }
    }

    // MARK:- PrepareForSegue

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        let name = textFeild?.text
        if var _ = socialMedia {
            self.socialMedia?.name = name!
        } else {
            socialMedia = SocialMedia(name:name!,imageName:"unknown")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

We have declared two variables socialMedia and index which will be populated when user taps an esitsing row in the TableView. Also you should find a IBOutlet for UITextField, make sure to connect this with TextField in the Interface Builder.

In the viewDidLoad function, if the user is editing an existing row then the textfield is updated with that value. The prepareForSegue method is called when the user taps Done or Cancel button. And based on the action, a new social media icon is added or an existing row is updated.

Navigate back to TableViewDemoController and implement the following function that will be called on cancel or done operation in DetailViewController.

//MARK:- Cancel and Done

    @IBAction func cancel(segue:UIStoryboardSegue) {
        // do nothing
    }

    @IBAction func done(segue:UIStoryboardSegue) {

        let detailViewController = segue.sourceViewController as!
        DetailViewController

        let socialMedia = detailViewController.socialMedia

        if let selectedIndex = index {
            data[selectedIndex] = socialMedia!
        } else {
            data.append(socialMedia!)
        }
        tableView.reloadData()
    }

Delete and Move row

Delete operation can be added by implementing the following function in TableViewDemoController.

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
	  switch editingStyle {
		case .Delete:
		// remove the deleted item from the model
	 	data.removeAtIndex(indexPath.row)
 		// remove the deleted item from the `UITableView`
		self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
	   	default:
		 return
   	}
}

This would allow users to swipe and delete a row in TableView. The function checks whether the editing style is Delete, then the row is removed from the array as well from the TableView display.

In order to allow users to move the rows, the tableView editing property needs to be set to true. Add another Bar Button Item, this time to the right of TableViewDemoController and provide the caption as Edit. Then connect this button with the following IBAction function.

//MARK:- Editing toggle

This button acts as a toggle switch to enable or disable tableview edit operation. Now add the following function required for Move operation.

//MARK:- TableViewCell Move row methods
	func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -&amp;gt; Bool {
     	return true
    }

Function canMoveRowAtIndexPath needs to return true and in moveRowAtIndexPath function, the tableView row data gets removed from the original index and inserted in to the new position.

Now the user can tap and hold the move option then drag and drop it to the desired position. When the tableview editing is set to true, it also provides delete button apart from the move operation.

Download the source code from here.

Social Media icons credit to Sebastiano Guerriero

Filed Under: ios, Swift, Uncategorized

Protocol Oriented Programming in Swift

March 10, 2016 By Ravi Shankar Leave a Comment

Object Oriented Programming is a paradigm used by programmers many decaded to solve computer problems by modeling them in to classes. In Swift 2.0 a new programming pattern has been introduced known as Protocol Oriented Programming. In this article, we will the three major feature as part of Protocol Oriented Programming

  • Modeling with Protocols and Structs
  • Protocol Extension
  • Swift Standard Library Extension

Using Protocols and Structs

Let us see an example by modeling Bicylce, MotorBike and Car with Protocols and Structs. Create Vehicle and MotorVehicle protocol with the following property definition

[code language=”swift”]protocol Vehicle {
var speed: Int {get}
var color: String {get}
var yearOfMake: Int {get}
}

protocol MotorVehicle {
var engineSize: Int {get}
var licensePlate: String {get}
}
[/code]

In Swift we can make any type (Class. Struct, Enums) to conform to a Protocol. Let us go for a value type (Struct) and not class as we are moving away from inheritance. And it is always safe to use value type and avoid memory related issues by using object references (Class).

[code language=”swift”]struct Bicyle: Vehicle {
let speed: Int
let color: String
let yearOfMake: Int
}

struct MotorBike: MotorVehicle, Vehicle {
let speed: Int
let color: String
let engineSize: Int
let licensePlate: String
let yearOfMake: Int
}
struct Car: MotorVehicle, Vehicle {
let speed: Int
let color: String
let engineSize: Int
let licensePlate: String
let numberOfDoors: Int
let yearOfMake: Int
}[/code]

In the above code snippet, we have created three strutcs Bicycle, MotorBike and Car. Bicyle conforms to Vehicle but Car and MotorBike conform to both Vehicle and MotorVehicle. Now start creating Cars, Bicycles and MotorBikes using corresponding structs.

[code language=”swift”]let cycle = Bicyle(speed: 10, color: “Blue”,yearOfMake: 2011)
let bike = MotorBike(speed: 65, color: “Red”, engineSize: 100, licensePlate: “HT-12345”,yearOfMake: 2015)
let bmw = Car(speed: 220, color: “Green”, engineSize: 1200, licensePlate: “FC-20 435”, numberOfDoors: 4,yearOfMake: 2016)
let audi = Car(speed: 220, color: “Cyan”, engineSize: 1200, licensePlate: “FC-41 234”, numberOfDoors: 4,yearOfMake: 2013)
[/code]

Protocol Extension

In Swift 2.0, the real power Protocol comes with its ability to add extension. It is not just adding method definition but now Protocol allows you to add implemenation as well. Let us say you want to compare vehicles based on yearOfMake attribute. All you need to do is to add an extension for Vehicle Protocol

[code language=”swift”]extension Vehicle {
func isNewer(item: Vehicle) -> Bool {
return self.yearOfMake > item.yearOfMake
}
}
// comparing audi and bmw should return false
audi.isNewer(bmw)[/code]

Swift Standard Library Extension

You can also add extension to Swift standard library such CollectionType, Range, Array etc.. Let us take the following scenario where you have an array of MotorBikes and want to filter them based on licensePlate information.

[code language=”swift”]let bike1 = MotorBike(speed: 65, color: “Red”, engineSize: 100, licensePlate: “HT-12345”,yearOfMake: 2015)
let bike2 = MotorBike(speed: 75, color: “Black”, engineSize: 120, licensePlate: “RV-453”,yearOfMake: 2013)
let bike3 = MotorBike(speed: 55, color: “Blue”, engineSize: 80, licensePlate: “XY-5 520”,yearOfMake: 2012)
let bike4 = MotorBike(speed: 55, color: “Red”, engineSize: 80, licensePlate: “XY-7 800”,yearOfMake: 2009)

let motorbikes = [bike1,bike2, bike3, bike4]
[/code]

How about filtering of all Small Mopeds based on licensePlate containing “XY” characters. This can be achieved by adding an extension to CollectionType which conforms to MotorVehicle protocol. Then create a new function “filterLicensePlate” as shown below

[code language=”swift”]extension CollectionType where Generator.Element:MotorVehicle {
func filterLicensePlate(match:String -> [Generator.Element] {
var result:[Generator.Element] = []
for item in self {
if item.licensePlate.containsString(match) {
result.append(item)
}
}
return result
}
} [/code][code language=”swift”]let motorbikes = [bike1,bike2, bike3, bike4]
// fiter only small mopeds based on XY
motorbikes.filterLicensePlate(“XY”).count
[/code]

Hope you found this introduction to Protocol Oriented Programming useful. Please use the comment section to add your feedback/suggestion.

References

WWDC 2015 – Protocol Oriented Programming
Mixing and Traits in Swift 2.0
Protocol-Oriented Programming in Swift 2
Introducing Protocol-Oriented Programming in Swift 2

Filed Under: ios, Swift 2 Tagged With: Protocol, Protocol Oriented Programming, Struct

  1. Pages:
  2. «
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. 9
  12. 10
  13. »
« Previous Page
Next Page »

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy