Cannot invoke 'self()' in beta 2

In XC6 and XC7b1 I was able to write code like this:


extension UILabel

{

class func myCustomCreator() -> Self

{

let s = self()

return s

}

}


This extension was available on UILabel and all sub classes of UILabel. In XC7b2, I get an error "cannot invoke 'self' with no arguments". I have not tried beta 3. Did something change? The release notes were not clear.

Answered by LCS in 24235022

I'm seeing the same problem with your code in Xcode 7 beta 3.

(You need to explictly include .init now, so you would have self.init() but that just gets you the similar error that init can't be invoked without arguments.)


It seems that the version of init() inherited from NSObject isn't being recognized when using .init() on a reference to a metatype.


This is probably a bug in the Swift compiler, since it seems to be applying the rules for Swift initializer inheritance to a class that has been imported from objC, when accessing it through a dynamic type object (like self in a type method, or a variable holding a metatype).


It recognizes the designated initializers inherited from UIView (which could be automatically inherited due to the rules for Swift initializer inheritance), but not designated initializers from ancestors past that point (which would be hidden in a Swift class after UIView declared it's own designated initializers).


As a workaround, you might be able to change your code to this:

extension UILabel
{
    class func myNewFunction() -> Self
    {
        let label = self.init(frame: CGRect())
        return label
    }
  
}

but I'm not sure if that would continue to work dynamically with subclasses.

Accepted Answer

I'm seeing the same problem with your code in Xcode 7 beta 3.

(You need to explictly include .init now, so you would have self.init() but that just gets you the similar error that init can't be invoked without arguments.)


It seems that the version of init() inherited from NSObject isn't being recognized when using .init() on a reference to a metatype.


This is probably a bug in the Swift compiler, since it seems to be applying the rules for Swift initializer inheritance to a class that has been imported from objC, when accessing it through a dynamic type object (like self in a type method, or a variable holding a metatype).


It recognizes the designated initializers inherited from UIView (which could be automatically inherited due to the rules for Swift initializer inheritance), but not designated initializers from ancestors past that point (which would be hidden in a Swift class after UIView declared it's own designated initializers).


As a workaround, you might be able to change your code to this:

extension UILabel
{
    class func myNewFunction() -> Self
    {
        let label = self.init(frame: CGRect())
        return label
    }
  
}

but I'm not sure if that would continue to work dynamically with subclasses.

Cannot invoke 'self()' in beta 2
 
 
Q