Passing a Swift protocol to an Objective-C pointer

<em>Using XCode 10.1 / Swift 4.2.</em>

Using XCode 10.1 / Swift 4.2.

I'm trying to assign an object that conforms to a Swift protocol to an Objective-C pointer. The following code is a minimal example that compiles and works as expected, but it gives me the following warnings:

If assigning to a local variable: Incompatible pointer types initializing 'NSObject<Animal> *__strong' with an expression of type 'id<Animal> _Nullable'

If assigning to a stored property: Incompatible pointer types assigning to 'NSObject<Animal> *' from 'id<Animal> _Nullable'

Any idea on how to address that warning without just silencing it?

Swift code:

@objc protocol Animal {
    var name: String { get }

@objc class Pig: NSObject, Animal {
var name: String = "pig"

@objc class Cow: NSObject, Animal {
var name: String = "cow"

@objc class Farm: NSObject {
static func getAnimal(name: String) -> Animal? {
// return some animal or nil

Objective-C code:

// This code returns a valid pointer to a Pig object
// that is usable in objective-c, but it also triggers
// the warning described above
NSObject<Animal>* animal = [Farm getAnimalWithName:@"pig"];

How to use Objective C Cocoapods in Swift Framework

My swift framework has dependency of Objective C Framework. How do I use that ?


When I try to use Bridging Header, I am getting error like Framework Target doesn't support Bridging Header

After my search , I found answers for

  1. How to use Objective C Files in Swift Framework
  2. How to use Objective C Framework with swift project

But I need solution for

How to use Objective C Framework as dependency in Swift Framework ?

Thanks in advance :)

A guide to Object Detection with OpenCV and Swift

A guide to Object Detection with OpenCV and Swift

In this article, we’ll see how to create and launch a object detection algorithm using OpenCV and Swift

Swift has been with us for a while now, and through its iterations, it has brought to us all the features of a modern object-oriented programming language. These include optionals, generics, tuples, structs that support methods, extensions and protocols, and many more. But if your application relies on a library that’s written using C++ then you can’t count on Swift anymore. Luckily Objective-C++ is here to help us.

Since its introduction, Swift has had great interoperability with Objective-C and we will use Objective-C for bridging Swift with C++. Objective-C++ is nothing more than Objective-C with the ability to link with C++ code, and using that, in this blog post, we will create a simple app that will recognize the Toptal logo inside the image using OpenCV. When we detect that logo, we’ll open the Toptal home page.

As stated on the OpenCV web page:

This is a great solution if you want fast to develop and reliable computer vision.

Creating the OpenCV Objective-C++ Wrapper

In this tutorial, we will design the application which will match a Toptal logo inside an image and open Toptal web page. To begin, create a new Xcode project and set up CocoaPods using pod init. Add OpenCV to Podfile pod 'OpenCV and run pod install in Terminal. Be sure to uncomment use_frameworks! statement inside Podfile.

Now, when we have OpenCV inside Xcode project, we have to connect it with Swift. Here is a quick outline of the steps involved:

Step 1: Create a new Objective-C class OpenCVWrapper. When Xcode asks you “Would you like to configure an Objective-C bridging header?” choose “Create bridging header.” The bridging header is the place where you import Objective-C classes, and then they are visible inside Swift.

Step 2: In order to use C++ inside Objective-C, we have to change the file extension from OpenCVWrapper.m to You can do it by simply renaming the file inside Xcode’s project navigator. Adding .mm as an extension will change the file type from Objective-C to Objective-C++.

Step 3: Import OpenCV into using the following import. It’s important to write the given import above #import "OpenCVWrapper.h" because this way we avoid a well-known BOOL conflict. OpenCV contains enum that has the value NO which causes a conflict with the Objective-C BOOL NO value. If you don’t need classes that use such enum, then this is the simplest way. Otherwise, you have to undefine BOOL before importing OpenCV.

#ifdef __cplusplus 
#import <opencv2/opencv.hpp> 
#import <opencv2/imgcodecs/ios.h> 
#import <opencv2/videoio/cap_ios.h> 

Step 4: Add #import "OpenCVWrapper.h" to your bridging header.

Open and create a private interface where we will declare private properties:

@interface OpenCVWrapper() <CvVideoCameraDelegate>
@property (strong, nonatomic) CvVideoCamera *videoCamera;
@property (assign, nonatomic) cv::Mat logoSample;

In order to create CvVideoCamera, we have to pass UIImageView to it, and we will do that through our designator initializer.

- (instancetype)initWithParentView:(UIImageView *)parentView delegate:(id<OpenCVWrapperDelegate>)delegate {
    if (self = [super init]) {
        self.delegate = delegate;
        parentView.contentMode = UIViewContentModeScaleAspectFill;
        self.videoCamera = [[CvVideoCamera alloc] initWithParentView:parentView];
        self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack;
        self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPresetHigh;
        self.videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
        self.videoCamera.defaultFPS = 30;
        self.videoCamera.grayscaleMode = [NSNumber numberWithInt:0].boolValue;
        self.videoCamera.delegate = self;
        // Convert UIImage to Mat and store greyscale version
        UIImage *templateImage = [UIImage imageNamed:@"toptal"];
        cv::Mat templateMat;
        UIImageToMat(templateImage, templateMat);
        cv::Mat grayscaleMat;
        cv::cvtColor(templateMat, grayscaleMat, CV_RGB2GRAY);
        self.logoSample = grayscaleMat;
        [self.videoCamera start];
    return self;

Inside it, we configure CvVideoCamera that renders video inside the given parentView and through delegate sends us cv::Mat image for analysis.

processImage: method is from CvVideoCameraDelegate protocol, and inside it, we will do template matching.

- (void)processImage:(cv::Mat&)image {
    cv::Mat gimg;
    // Convert incoming img to greyscale to match template
    cv::cvtColor(image, gimg, CV_BGR2GRAY);
    // Get matching
    cv::Mat res(image.rows-self.logoSample.rows+1, self.logoSample.cols-self.logoSample.cols+1, CV_32FC1);
    cv::matchTemplate(gimg, self.logoSample, res, CV_TM_CCOEFF_NORMED);
    cv::threshold(res, res, 0.5, 1., CV_THRESH_TOZERO);
    double minval, maxval, threshold = 0.9;
    cv::Point minloc, maxloc;
    cv::minMaxLoc(res, &minval, &maxval, &minloc, &maxloc);
    // Call delegate if match is good enough
    if (maxval >= threshold)
        // Draw a rectangle for confirmation
        cv::rectangle(image, maxloc, cv::Point(maxloc.x + self.logoSample.cols, maxloc.y + self.logoSample.rows), CV_RGB(0,255,0), 2);
        cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
        [self.delegate openCVWrapperDidMatchImage:self];

First, we convert the given image to grayscale image because inside the init method we converted our Toptal logo template matching image to grayscale. Next step is to check for matches with a certain threshold which will help us with scaling and angles. We have to check for angles because you can capture a photo in various angles in which we still want to detect logo. After reaching the given threshold we will invoke delegate and open Toptal’s web page.

Don’t forget to add NSCameraUsageDescription to your Info.plist otherwise, your application will crash right after calling [self.videoCamera start];.

Now Finally Swift

So far we were focusing on Objective-C++ because all the logic is done inside it. Our Swift code will be fairly simple:

  1. Inside ViewController.swift, create UIImageView where CvVideoCamera will render content.
  2. Create an instance of OpenCVWrapper and pass the UIImageView instance to it.
  3. Implement OpenCVWrapperDelegate protocol to open Toptal’s web page when we detect the logo.
class ViewController: UIViewController {
    var wrapper: OpenCVWrapper!
    @IBOutlet var imageView: UIImageView!
    override func viewDidLoad() {
        wrapper = OpenCVWrapper.init(parentView: imageView, delegate: self)
extension ViewController: OpenCVWrapperDelegate {
    //MARK: - OpenCVWrapperDelegate
    func openCVWrapperDidMatchImage(_ wrapper: OpenCVWrapper) {
 "")!, options: [:], completionHandler: nil)

OpenCV Swift in Action

In this article, we have shown how you can integrate C++ code with Swift and create wrapper classes that are here for bridging C++ code with Swift. Now, when we detect the Toptal Logo through the camera, we open Toptal’s home page.

For future updates, you may want to run CV template matching in a background thread. This way, you won’t block the main thread and the UI will stay responsive. Because this is a simple example of OpenCV, template matching may not be extra successful, but the purpose of this article was to show you how you can start using it.

Thanks for reading


Follow us on Facebook | Twitter

Further reading about OpenCV and Python

Complete Python Bootcamp: Go from zero to hero in Python 3


Python and Django Full Stack Web Developer Bootcamp

Computer Vision Using OpenCV

OpenCV Python Tutorial - Computer Vision With OpenCV In Python

Python Tutorial: Image processing with Python (Using OpenCV)

A guide to Face Detection in Python

Machine Learning Tutorial - Image Processing using Python, OpenCV, Keras and TensorFlow

Face Detection using Open-CV

Swift vs. Objective-C: The trending up-and-comer vs. the dinosaur

I remember how pivotal it was when Swift was introduced at Apple’s 2014 WWDC (Worldwide Developers Conference). It was the talk of the town and all the devs I worked with couldn’t wait to try it out. The iOS community was buzzing and there was a lot of excitement around the new language.

A short history of Swift


It was developed in order to carry on some concepts we saw in Objective-C such as extensible programming. But it pushed towards a different approach to coding with the protocol-oriented design and increased safety with static typing.

It was a huge hit and saw its growth sky rocket in the years after introduction. It was the most loved programming language in 2015, the second most lovedin 2016, the 11th most popular programming language in 2017, beating out Objective-C, and it also beat out Objective-C in 2018.

Swift is also a bet by Apple on winning over novices to become iOS developers. The hope is that new developers will learn the language and use it to build iOS apps. This then increases the ecosystem of the app store. Since Swift is optimized to work with iOS apps, this ensures the apps being written are of high quality.

Swifts popularity only continues to increase, especially for smaller apps and start-ups. The gap between Swift and Objective-C will only continue to grow. The future is bright for this young language.

A short history of Objective-C

Objective-C is an object-oriented programming language that is a superset of C, as the name of the language might reveal. This means that any valid C program will compile with an Objective-C compiler. It derives all its non-object oriented syntax from C and its object oriented syntax from SmallTalk. It was developed in 1984, so it has had time to mature as a language and is much more stable than Swift.

Most people know Objective-C as the language that is used to develop apps for the iPhone, but the history goes much deeper than that. I’d recommend reading this article for a more in-depth look.

The strengths of Swift

Swift has grown tremendously in popularity for a few key reasons. First off, there are a lot of great development tools Apple has provided to work in conjunction with Swift. One of my personal favorites is the Playground, which is only compatible with Swift. Apple introduced Playgrounds in 2016. They were introduced as a way to learn how to code, but I loved them for a different reason.

Mobile development has always had more roadblocks than web development. You need a simulator, you usually need a proprietary Integrated Development Environment (IDE), and you need to set up a whole project just to test some small prototype. In Apple’s case, you also need a developer account. The nice thing about Playgrounds is you get around some of this. You do need Xcode or the Playgrounds app, but that is all. And you can get started with coding and compiling your code right away.

Yet, another huge advantage of Swift is the fact that it is open source. If you have ever wondered how a programming language worked under the hood, then you can go see for yourself! This is a great way to understand the programming language you work with daily on a deeper level.

An honorable mention goes to a nice utility only available to Swift, the Swift Package Manager. The Swift Package Manager is simply a dependency manager that is integrated with the Swift build system. It isn’t a game changer by any means, since CocoaPods and Carthage were doing this job a long time ago, but it’s another solution available if needed.

A lot of evidence here supports the fact that Apple is doing a lot to make Swift more desirable as the programming language of choice for iOS developers. They are creating nice utilities and auxiliaries to entice people to start using the language. This shows that Apple is pushing for Swift in full force.

Language features

Let’s get into some of the details of the language itself. Swift is safer due to its static typing and the use of optionals. In Swift, if your code requires a string, the features of Swift will guarantee that your code gets a string and not another type, such as an int. This of course depends on if you’re using the language as it is intended and not force unwrapping everything.

func checkString(_ string: String?) {
    // Good, verifying parameters aren't nil.
    if let string = string {
        print(string + " is a string")
// Bad, we circumvent the safety features
// by using forced unwrapping (!).
print(string! + " is a string")

// Create a nil var
var myString: String?
// This will crash due to our use of forced unwrapping.
// Fatal error: Unexpectedly found nil while
// unwrapping an Optional value

Another great feature of Swift is its syntax. Especially compared to Objective-C. The best word to describe the syntax would be “succinct”. There is no need for semi-colons, calls to self or parentheses around if statements. It feels like you are skipping a lot of things that you don’t really need anyway. It can make the process of typing a lot of code “flow” better.

Some people say this leads to development velocity improvements, but I wouldn’t exactly say that myself. The continual need to unwrap objects to comply with Swifts type-safety offsets the development gains that come with the succinctness.

Swift also has a lot of great control flow options with guard, if-let, advanced switch statements, repeat-while and defer. I like all the different options because it lets people control the flow of their code in a way that makes sense to them. A lot of people hate defers but love guards and vice versa. It doesn’t really matter what you like or dislike, but the options are there and you can code in the way that feels best to you.

func checkString(_ string: String?) {
defer {
if string == nil {
print("The string is nil. Can't print.")
} else {
print("Successfully printed the string")
guard let string = string else { return }
var i = 0;
repeat {
// Strings are weird in Swift
print(string[string.index(string.startIndex, offsetBy: i)])
} while ( i < string.count)

var myString: String?


Successfully printed the string
The string is nil. Can't print.

I can’t forget all the functional programming features such as filter, map and reduce. This is great for handling collections and comes in handy quite often.

The weaknesses

Swift is a young language, and with that, comes some shifting. The migrations between versions are simply a pain. At a small company, the migration tool provided by Apple can be helpful and cover most cases. It becomes less helpful the more code you have. It’s even worse if your codebase contains both Objective-C and Swift code that interoperate.

At my last company, the migration effort took a dedicated group a whole weekend to do. They had to do it on the weekend so that they wouldn’t run into merge conflicts from other devs pushing code. This was incredibly painful for everyone involved.

A reason for these migrations is the fact that Swift isn’t ABI stable. That means newer versions of Swift cannot work with older versions of Swift. That also means that the language cannot be packaged with the OS. This is a big deal for companies with large apps that actively combat app size because Swift is being bundled with the app and increasing the size.

Another issue is that Swift does not play well with Xcode. Xcode feels very choppy when working with Swift and autocomplete simply doesn’t worksometimes. This is strange given how hard Apple is pushing Swift. You would think that they would want make the experience of using Swift with Xcode a delight.

Swift also has problems with string handling, see the code example above. It is clunky as hell. In your day to day, this isn’t too bad. Where this comes into play the most is during interviews. Unfortunately for Swift devs, interviewers love asking questions that involve string manipulation. This is compounded by the fact that the way strings are handled has changed between versions of Swift.

The strengths of Objective-C

Objective-C is a highly dynamic, object oriented language. It is dynamic to the point that you can swap out method invocations at runtime using techniques like Swizzling. It is able to do these kinds of thing due to its message sending paradigm. This lets objects send messages to other objects at run time to determine the invocation of the method being called.

In practical purposes, what does this mean? Well, one big advantage is adaptability at runtime. This means accessing private APIs or doing things like mocking objects at runtime become possible. This can be especially useful when it comes to unit testing. Libraries like OCMock make this even easier and allow for very elaborate test set ups. Having good unit tests will make your app more stable and reliable.

Speaking of stability, Objective-C has been around for a long time which makes it a very stable language. With Swift, you’ll run into bugs that are pretty surprising and would be disruptive to the stability of your app. In the example I linked above, this crash would be caused by the actual language you are using to code your app, not due to any error created by the code you wrote. This can be frustrating.

The last point, which is more important to certain companies, is compatibility with C and C++ libraries. Being that Objective-C is a superset of C, it is easy to use C and C++ code with Objective-C. You can even use Objective-C++ if you feel so inclined. This is important if your are dependent on third party C and C++ libraries.

The weaknesses

The first main complaint I hear about Objective-C is syntax. I started my professional career using Objective-C so I have no issues with it. It is verbose and a bit unconventional with the use of square brackets. But opinions on syntax are just that, opinions. I figured I would list this point though since it is one of the first things that comes up when you mention Objective-C.

One thing I do agree with though is that block syntax is frustrating. There is even a website dedicated to decoding the mysteries of blocks in Objective-C. I actually use this website pretty often as a reference.

[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(doStuff:)
name: @"Notification"
object: nil];

The biggest issue Objective-C faces right now is the fact that one day Apple may drop support for Objective-C with Cocoa and other common libraries used to create iOS apps. Since Objective-C is primarily used to create iOS apps, this would be a death knell for the language. It also means that newcomers to the iOS community are afraid to commit to learning Objective-C right now since it may no longer be used in the future.

Let’s get back to the language itself. It is prone to having hard to debug issues due to the dynamic nature of the language. The ability to send messages to nil and not crash on top of the lack of strict typing are some examples of things that lead to these hard to debug issues.

Objective-C does not hold your hand when it comes to these things either. Though it is nice that the app doesn’t crash when you send a message to nil, it may put your app in a weird state. It is very hard to debug issues like these. The fact that Swift has strict typing and the use of unwrapping optionals prevents these things at compile time.

Should I learn Swift or Objective-C?

The answer for most people will be Swift. Apple is clearly pushing Swift as the language of choice for its iOS application development community. Swift will only continue to become more performant as ABI stability is introduced and Swift becomes packaged with the OS itself.

If you’re looking to get a job as an iOS developer, Swift will be the language you want to learn. Most startup to mid-level companies will have their iOS apps written completely in Swift. This means you’ll be able to apply and interview for more jobs if you learn Swift.

Even at larger companies where Objective-C is still used heavily, interviews can still be done in Swift. So you can learn Objective-C once you join the company and not worry about burdening yourself with more things to learn before the interview.

You will want to learn Objective-C if you are already working at a start up or mid-level company and want to jump to a larger company. Skills with Objective-C will give you specialized knowledge and an edge over other interview candidates.

By : Colin Smith