Self.Type cannot be directly converted in AnyClass to an extension to the objective-c class in swift

I am trying to create a fabric method to create a UIViewController with the correct nib name (to fix the default IOS8 initialization error). For this, I added the extension:

extension UIViewController {    
    class func create() -> Self {
        if #available(iOS 9.0, *) {
            return self.init()
        } else {
            let clsName = NSStringFromClass(self).componentsSeparatedByString(".").last!
            return self.init(nibName: clsName, bundle: nil)
        }
    }
}

However, the compiler throws an error: Cannot convert value of type 'Self.Type' to expected argument type 'AnyClass' (aka 'AnyObject.Type')c NSStringFromClass(self).

To fix this, you can add another extension method and rewrite the code:

extension UIViewController {
    private class var nibNameForInitializer:String {
        return NSStringFromClass(self).componentsSeparatedByString(".").last!
    }
    class func create_() -> Self {
        if #available(iOS 9.0, *) {
            return self.init()
        } else {
            return self.init(nibName: self.nibNameForInitializer, bundle: nil)
        }
    }
}

However, I want to understand the problem with the first option.

As I understand it, the returning method Selfis a kind of universal method. Selfcan be used in many contexts (for example, class, structure, protocol, etc.), but Self.Typecorresponds to AnyClassonly classes.

, Self UIViewController ( UIViewController), Self.Type AnyClass.

- , , - Self?

+4
2

() , Apple. Self.

let clsName = NSStringFromClass(self as! AnyClass).componentsSeparatedByString(".").last!

.

:

// Swift 2:
let clsName = String(self)
// Swift 3:
let clsName = String(describing: self)
+8

, , downcast, :

let clsName = NSStringFromClass(self as! AnyClass).componentsSeparatedByString(".").last!
+2

Source: https://habr.com/ru/post/1614740/


All Articles