Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterless Failable initializer for an NSObject subclass

Tags:

ios

swift

I'd like to provide a failable initializer to an NSObject subclass for the initialization without parameters. My overall goal is to return nil this class is initialized on an OS version less than 8.0.

My attempt at this is below:

class MyObject: NSObject {
    override init?() {
        super.init()
        if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 {
            return nil
        }

    }
}

However this code results in the following compiler error.

Failable initializer 'init()' cannot override a non-failable initializer

Is it possible to override init() to provide a failable implementation in a subclass? Or is there a better way to achieve this goal?

like image 799
Glen T Avatar asked Nov 09 '14 22:11

Glen T


1 Answers

As you are subclassing NSObject, you cannot have a failable no-parameter initialiser as NSObject's no parameter initialiser is not failable.

You could create a class factory method that returns an instance or nil depending on the iOS version

like image 97
Paulw11 Avatar answered Oct 06 '22 00:10

Paulw11