0

here I have a class function public class func testing() -> Self:

public extension UIViewController {
    public class func testing() -> Self {
        return getInstance()
    }
}

and a getInstance() -> UIViewController function which I can't be modified:

public func getInstance() -> UIViewController {
    return UIViewController()
}

now, how to cast the return value of getInstance() function to Self in testing() function?

return getInstance() // error
return getInstance() as! Self // error
return getInstance() as! UIViewController // error
Meniny
  • 660
  • 8
  • 22

1 Answers1

2

Just change your function to

public extension UIViewController {
    public class func testing() -> UIViewController {
        return getInstance()
    }
}

The function needs to specify a return Type which in this case would always be UIViewController as thats the type you extend.

Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • thx. But I want to return a `Self` type instead of `UIViewController` type, so I can get the right type by calling this function from subclasses. – Meniny Jan 05 '18 at 10:22
  • Than you might be able to do it with Generics. if you are returning a type which is only determined at runtime then you have no way to cast another type to this unknown type. Generics would be the only way to do this that I know of – Scriptable Jan 05 '18 at 10:23