Date
Sep. 8th, 2024
 
2024年 8月 6日

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.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系