Date
Jul. 14th, 2024
 
2024年 6月 9日

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
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF