Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Self in Swift

Tags:

ios

swift

Aim: to make a generic ViewController and TableViewController which would be able to return themselves from the existing storyboards and which would be subclassed by other view controllers and allow them to use this functionality.

class GenericTableViewController: UITableViewController
{
    //MARK: Storyboard
    class func storyboardName() -> String
    {
        return ""
    }

    class func storyboardIdentifier() -> String
    {
        return ""
    }

    class func existingStoryboardControllerTemplate() -> Self
    {
        return  UIStoryboard.storyboardWithName(storyboardName()).instantiateViewControllerWithIdentifier(storyboardIdentifier()) as! Self
    }
}

The problem is.. the compiler forces me to change the Self to this "GenericTableViewController" and if I change it... it complains that I no longer return "Self".

Is there something that can fix this?

like image 851
Fawkes Avatar asked Jun 13 '15 07:06

Fawkes


1 Answers

Doing the following should work:

class func existingStoryboardControllerTemplate() -> Self {
    return  existingStoryboardControllerTemplate(self)
}

private class func existingStoryboardControllerTemplate<T>(type: T.Type) -> T {
    return  UIStoryboard(name: storyboardName(), bundle: nil).instantiateViewControllerWithIdentifier(storyboardIdentifier()) as! T
}

Basically you create a generic version of your existingStoryboardControllerTemplate and add an extra method to help the compiler infer the type of T.

like image 180
Tomas Camin Avatar answered Sep 30 '22 19:09

Tomas Camin