Skip to content

Swift compiler don't detect missing default initializer in generic at compile time.Β #85273

@barabashd

Description

@barabashd

Description

The Swift compiler accepts generic <T: UIView> code that calls a default init from that type - T() without verifying that the generic type parameter T has a default initializer still available. This results in a runtime crash instead of a compile-time error, representing a gap in Swift's type system checking.

The issue occurs when a UIView subclass overrides init without providing a default initializer, but the compiler still allows T() instantiation in generic contexts where T: UIView. This creates a silent failure mode where compile-time constraints don't match runtime requirements, undermining Swift's safety guarantees.
This affects common SwiftUI development patterns where developers create reusable generic UIViewRepresentable components, making it a practical rather than theoretical concern.

Reproduction

// call this to reproduce a crash
_ = ViewThatCrash<CustomView>()

struct ViewThatCrash<T: UIView>: UIViewRepresentable {
  func makeUIView(context: Context) -> T {
    T() // crash here
  }
  
  func updateUIView(_ uiView: T, context: Context) {}
}

class CustomView: UIView {
  // changed default init
  init(from str: String) { super.init(frame: .zero) }
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

Stack dump

TestApp/TestView.swift:21: Fatal error: Use of unimplemented initializer 'init(frame:)' for class 'TestApp.TestView'
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x100c2204c)

Expected behavior

The compiler should detect this issue at compile-time and provide one of the following:

  • Compile-time error indicating that T() cannot be called because T doesn't guarantee a default initializer is available.
  • Compiler warning about potentially unsafe T() instantiation in generic contexts

The current behavior violates Swift's principle of compile-time safety by allowing code that will predictably crash at runtime. The constraint T: UIView should either guarantee that T() is safe to call, or the compiler should warn/error when T() is used without such guarantees.

Environment

swift-driver version: 1.127.14.1 Apple Swift version 6.2 (swiftlang-6.2.0.19.9 clang-1700.3.19.1)

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.crashBug: A crash, i.e., an abnormal termination of softwaretriage neededThis issue needs more specific labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions