You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UIViewController默认初始化器定义位置?Xcode版本编译差异咨询

Understanding UIViewController's Hidden Default Initializer

Hey there, let's clear up this confusion for you—this is a common gotcha when working with Swift and UIKit's Objective-C roots!

Why You Could Use init() But Couldn't See Its Definition

First off: the default init() you were using isn't actually defined in the Swift interface of UIViewController that you see in Xcode. Instead, it comes from UIKit's Objective-C implementation and how Swift interacts with Objective-C classes.

UIViewController inherits from NSObject (via UIResponder), which has the classic init method in Objective-C. In UIKit's Objective-C code, UIViewController overrides this init method internally to call its designated initializer:

- (instancetype)init {
    return [self initWithNibName:nil bundle:nil];
}

This is exactly what the comment refers to when it says "the default init method will do this for you, and specify nil for both of this method's arguments."

In older Swift versions (like the one in Xcode 11.0/Swift 5.1), Swift would implicitly recognize this Objective-C init method and let you call it in your code, even though it wasn't exposed in the Swift header.

Why Xcode 11.2.1 Broke the Compilation

Starting with Xcode 11.2 (which uses Swift 5.1.2), Apple tightened up how Swift imports Objective-C initializers. Now, if an Objective-C class doesn't explicitly declare an init method in its interface (which UIViewController doesn't—only init(nibName:bundle:) and init?(coder:) are declared), Swift no longer assumes the default init() exists. That's why your code that worked in Xcode 11.0 started throwing errors in 11.2.1.

Your Temporary Fix Is Correct

Adding those three initializers to your subclass is the right approach to comply with Swift's initialization rules. For reference, here's what that looks like:

class MyViewController: UIViewController {
    // Default initializer, matching the Objective-C behavior
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    // Designated initializer from UIViewController
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    // Required for NSCoder support
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

This ensures your subclass properly covers all the initialization paths expected by Swift and UIKit.

内容的提问来源于stack exchange,提问作者jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:57:03