Date
Jan. 23rd, 2025
 
2025年 12月 24日

Post: Swift: Return instancetype

Swift: Return instancetype

Published 12:01 Jan 05, 2018.

Created by @ezra. Categorized in #Programming, and tagged as #iOS.

Source format: Markdown

Table of Content

To return instancetype in Swift, you can define a generic helper method which infers the type of self from the calling context:

public extension UIViewController {
    // Call this
    public class func instance(storyboard sbname: String, bundle: Bundle? = nil, identifier: String?) -> Self {
        return helper_instance(storyboard: sbname, bundle: bundle, identifier: identifier)
    }

    // Helper
    private class func helper_instance<T>(storyboard sbname: String, bundle: Bundle?, identifier: String?) -> T {
        let storyboard = UIStoryboard.init(name: sbname, bundle: bundle)
        guard let id = identifier else {
            return storyboard.instantiateInitialViewController() as! T
        }
        return storyboard.instantiateViewController(withIdentifier: id) as! T
    }
}

then:

let controller = MyController.instance(storyboard: "Main", identifier: "MyController")

compiles, and the type is inferred as MyController now.

Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
开发、设计与写作皆为所长。
热爱苹果、钟情色彩。
随时恭候 垂询